[英]How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?
我正在使用以下內容在我的 C# 應用程序中加載一個 XML 文檔:
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
但在此之前,我會進行測試以確保該文件存在:
File.Exists(myfile);
但是......是否有一種(簡單的)方法可以在 XDocument.Load() 之前測試文件以確保它是一個有效的 XML 文件? 換句話說,我的用戶可能會不小心點擊文件瀏覽器中的不同文件並嘗試加載,比如說,一個 .php 文件會導致異常。
我能想到的唯一方法是將它加載到 StreamWriter 中,然后簡單地對前幾個字符進行文本搜索,以確保它們說“
謝謝!
-阿迪娜
如果您想向用戶顯示一條消息,那么捕獲特定異常可能是值得的:
try
{
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
}
catch (XmlException exception)
{
ShowMessage("Your XML was probably bad...");
}
根據定義,有效的 xml 文檔是格式良好的文檔。 此外,它必須滿足DTD或模式( xml 模式、 relaxng 模式、 schematron或其他約束)才有效。
從問題的措辭來看,很可能它會問:
“如何確保文件包含格式良好的 XML 文檔?”。
答案是,如果 XML 文檔可以被兼容的 XML 解析器成功解析,那么它就是格式良好的。 由於XDocument.Load()方法正是這樣做的,因此您只需捕獲異常,然后得出文件中包含的文本格式不正確的結論。
只需加載它並捕獲異常。 File.Exists()
也是如此——文件系統是易變的,所以僅僅因為File.Exists()
返回 true 並不意味着你將能夠打開它。
如果您有 XML 的 XSD,請嘗試以下操作:
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD
{
public static void Main()
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read());
}
// Display any warnings or errors.
private static void ValidationCallBack (object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
參考在這里:
http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.validationeventhandler.aspx
正如前面提到的,“有效的 xml”是由 XmlDocument.Load() 測試的。 只需捕獲異常。 如果您需要進一步驗證以測試它對架構是否有效,那么這將執行您的操作:
using System.Xml;
using System.Xml.Schema;
using System.IO;
static class Program
{
private static bool _Valid = true; //Until we find otherwise
private static void Invalidated()
{
_Valid = false;
}
private static bool Validated(XmlTextReader Xml, XmlTextReader Xsd)
{
var MySchema = XmlSchema.Read(Xsd, new ValidationEventHandler(Invalidated));
var MySettings = new XmlReaderSettings();
{
MySettings.IgnoreComments = true;
MySettings.IgnoreProcessingInstructions = true;
MySettings.IgnoreWhitespace = true;
}
var MyXml = XmlReader.Create(Xml, MySettings);
while (MyXml.Read) {
//Parsing...
}
return _Valid;
}
public static void Main()
{
var XsdPath = "C:\\Path\\To\\MySchemaDocument.xsd";
var XmlPath = "C:\\Path\\To\\MyXmlDocument.xml";
var XsdDoc = new XmlTextReader(XsdPath);
var XmlDoc = new XmlTextReader(XmlPath);
var WellFormed = true;
XmlDocument xDoc = new XmlDocument();
try {
xDoc.Load(XmlDoc);
}
catch (XmlException Ex) {
WellFormed = false;
}
if (WellFormed & Validated(XmlDoc, XsdDoc)) {
//Do stuff with my well formed and validated XmlDocument instance...
}
}
}
根據接受的答案,我不會 XDocument.Load(); 為什么要將整個文件讀入內存,它可能是一個巨大的文件?
我可能會將前幾個字節讀入 byteArray(它甚至可以是任何二進制文件),將 byteArray 轉換為字符串,例如System.Text.Encoding.ASCII.GetString(byteArray)
,檢查轉換后的字符串是否包含 Xml 元素你在期待,然后才繼續。
我知道這個線程已經有將近 12 年的歷史了,但我仍然想添加我的解決方案,因為我在其他任何地方都找不到它。 我認為你想要的只是一種檢查文件是否為 xml 文件的方法,而不是文件是否結構良好或其他任何東西。 (這就是我對問題的理解)。
我找到了一種方法可以輕松檢查文件是否為 xml 文件(或您需要的任何文件,這適用於任何情況),這將是以下代碼行:
new System.IO.FileInfo(filePath).Extension == ".xml"
只需將“filePath”替換為您的文件路徑即可。 您可以將語句放在需要布爾值的任何地方。
你可以這樣使用它:
boolean isXmlFile = new FileInfo("c:\\config.xml").Extension == ".xml" //will return true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.