今天采用Xpath讀取Xml節(jié)點(diǎn),怎么都讀不出。
問(wèn)題分析:
錯(cuò)誤代碼如下:
XmlDocument xmlD = new XmlDocument();
xmlD.PreserveWhitespace = true;
xmlD.LoadXml(xStr);
xmlD.SelectNodes(@"job-scheduling-data/schedule/job");
經(jīng)排查 dotnet 文檔,發(fā)現(xiàn)代碼編寫(xiě)沒(méi)有問(wèn)題。文檔描述如下:
文檔示例如下:
示例代碼:
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:samples");
//Select and display the value of all the ISBN attributes.
XmlNodeList nodeList;
XmlElement root = doc.DocumentElement;
nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);
foreach (XmlNode isbn in nodeList){
Console.WriteLine(isbn.Value);
}
}
}
示例XML:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-691316.html
<?xml version="1.0"?>
<!-- A fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
<book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>29.95</price>
</book>
<book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
<title>Emma</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
<title>Sense and Sensibility</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>
自己程序采用Xml:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-691316.html
結(jié)論:?jiǎn)栴}原因:最后用文檔示例與自己代碼比較發(fā)現(xiàn)上命名空間導(dǎo)致**
修改后正確代碼
string xStr = File.ReadAllText(path.Trim());
xStr = xStr.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
xStr = xStr.Replace("xmlns=\"http://quartznet.sourceforge.net/JobSchedulingData\"", "");
xStr = xStr.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
XmlDocument xmlD = new XmlDocument();
xmlD.PreserveWhitespace = true;
xmlD.LoadXml(xStr);
XmlNodeList jobNodeList = xmlD.SelectNodes(@"job-scheduling-data/schedule/job");
到了這里,關(guān)于XmlDocument.SelectNodes 不起作用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!