我正在處理一些在運行時加載xml文件的代碼。在那一刻,我們使用XmlDocument類型來讀取xml文件並圍繞SelectSingleNode語句包裝一個try-catch(這是在一個節點爲空或不存在的情況下完成的,因爲我們解析用戶創建xml文件)。在C#中使用模式進行XML解析#
請注意:我意識到XmlDocument已被替換爲XDocument。但是,由於我們正在使用.NET版本3(according to this MSDN document XDocument在.NET 3中不可用),所以我們現在必須堅持使用XmlDocument。我們使用.NET 3的原因有很多(其中一些與規範相關)。
下面是我們在一分鐘做什麼的例子:
private void LoadUserXMLFile()
{
XmlDocument xDoc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(fileName);
reader.Read();
xDoc.Load(reader);
try { firstElementString = xDoc.SelectSingleNode(<path to node>).InnderText);
catch { <exception handling here > }
//more SelectSingleNode statements, each wrapped inside
//individual try-catch blocks
}
顯然,上面是一個例子,我已經簡化catch語句。
我已經爲用戶生成的XML文件編寫了一個模式,該應用程序可以使用,並且我想知道如果我在解析XML文檔時使用了模式(以某種方式),是否仍然需要打包每個SelectSingleNode都帶有try-catch語句?
甚至可以在解析過程中使用模式(以某種方式)檢查XML文檔是否具有正確的格式和所有必需的元素?