C# XML解析方式實(shí)例解析
C# XML解析通過(guò)XPath的方式是如何辦到的呢?具體的操作步驟是什么呢?那么下面我們就向你介紹通過(guò)XPath的方式來(lái)實(shí)現(xiàn)C# XML解析,希望對(duì)你了解C# XML解析有所幫助。
C# XML解析通過(guò)XPath的方式的步驟:
1、需要先加載文檔,然后再讀取想要的節(jié)點(diǎn)值。
◆xml文檔
protected XmlDocument doc = null;
◆xml文檔的根元素(節(jié)點(diǎn))
protected XmlElement root = null;
◆xml文檔的名空間管理器
protected XmlNamespaceManager nsmgr = null;
2、接下來(lái)就是加載文檔了
- protected void LoadXmlFile(FileInfo xmlFile)
- {
- if (xmlFile == null || !xmlFile.Exists)
- {
- throw new FileNotFoundException(
- string.Format("要解析的文件不存在{0}。",
- xmlFile.FullName));
- }
- //加載文件
- this.doc = new XmlDocument();
- doc.Load(xmlFile.FullName);
- //準(zhǔn)備讀取文件
- root = doc.DocumentElement;
- string nameSpace = root.NamespaceURI;
- nsmgr = new XmlNamespaceManager(doc.NameTable);
- nsmgr.AddNamespace("ns", nameSpace);
- }
◆C# XML解析通過(guò)XPath的方式要注意。
a、這兩行是取得xml文檔的名空間
- root = doc.DocumentElement;
- string nameSpace = root.NamespaceURI;
b、這兩行是建立xml文檔的名空間管理器
- nsmgr = new XmlNamespaceManager(doc.NameTable);
- nsmgr.AddNamespace("ns", nameSpace);
如果你的xml文檔有名空間,則這部分的代碼是必不可少的。
3、接下來(lái)就是讀取文檔節(jié)點(diǎn)的值了
這里兩個(gè)傳入?yún)?shù)prefixPath是節(jié)點(diǎn)的上級(jí)節(jié)點(diǎn)路徑,xRelativePath是要讀取的節(jié)點(diǎn)名稱。
另外,變量XmlFileInfo是要加載的xml文件。
- protected string GetNodeValue(
- string prefixPath, string xRelativePath)
- {
- if (doc == null)
- {
- LoadXmlFile(XmlFileInfo);
- }
- string xPath = string.Empty;
- if (!string.IsNullOrEmpty(xRelativePath))
- {
- if (!string.IsNullOrEmpty(prefixPath))
- {
- xPath = prefixPath + xRelativePath;
- }
- else
- {
- xPath = xRelativePath;
- }
- }
- xPath = xPath.Replace("/", "/ns:");
- XmlNode node = root.SelectSingleNode(xPath, nsmgr);
- if (node == null)
- {
- return null;
- }
- return node.InnerXml;
- }
可能有的朋友要問(wèn),為什么要設(shè)置兩個(gè)參數(shù)prefixPath和xRelativePath呢,其實(shí)這個(gè)沒(méi)有多大的關(guān)系,我只是為了自己覺(jué)得方便,你也可以在方法外確定了這個(gè)XPath,在方法中只設(shè)置一個(gè)傳入?yún)?shù),效果是一樣的。
◆注意這一行:
- xPath = xPath.Replace("/", "/ns:");
如果你的xml文檔帶名空間,則這行是比不可少的,否則會(huì)出現(xiàn)找不到節(jié)點(diǎn),無(wú)法解析的情況。
關(guān)于XPath的一些問(wèn)題:
對(duì)于這樣一個(gè)xml文檔,要查找第一個(gè)節(jié)點(diǎn)下的學(xué)生的Name時(shí)(ID=01),其XPath應(yīng)該是"/ns:Root/ns:Students/ns:Student[1]/ns:Name"。xml對(duì)于重復(fù)的節(jié)點(diǎn)名稱,是按照順序1,2,3...的方式遍歷的,也就是說(shuō)如果要找第N個(gè)Student節(jié)點(diǎn)的下的節(jié)點(diǎn)之,那么應(yīng)使用Student[N]的標(biāo)識(shí)方式。
- ﹤?xml version="1.0" encoding="UTF-8" ?﹥
- ﹤Root xmlns="urn:ClassNameSpace"﹥
- ﹤Class﹥
- ﹤ClassID﹥1234﹤/ClassID﹥
- ﹤/Class﹥
- ﹤Students﹥
- ﹤Student﹥
- ﹤ID﹥01﹤/ID﹥﹤Name﹥Name01﹤/Name﹥
- ﹤/Student﹥
- ﹤Student﹥
- ﹤ID﹥02﹤/ID﹥﹤Name﹥Name02﹤/Name﹥
- ﹤/Student﹥
- ﹤/Students﹥
- ﹤/Root﹥
當(dāng)然,這里也可以獲取節(jié)點(diǎn)屬性的值,查找滿足特定值的節(jié)點(diǎn)等等,這些和上面獲取節(jié)點(diǎn)值的過(guò)程是類似的。
C# XML解析通過(guò)XPath的方式的實(shí)現(xiàn)就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C# XML解析有所幫助。
【編輯推薦】