[英]Reading XML using XmlDocument
這是我的飼料。
<feed xml:lang="">
<title>NEWS.com.au | Top Stories</title>
<link rel="self" href="http://feeds.news.com.au/public/atom/1.0/news_top_stories_48_48.xml"/>
<link rel="alternate" href="http://news.com.au"/>
<id>http://news.com.au</id>
<rights/>
<entry>
<title>F1’s glaring issues exposed</title>
<link href="www.google.com"/>
<author>
<name>STEVE LARKIN</name>
</author>
<link rel="enclosure" type="image/jpeg" length="2373" href="abc.jpg"/>
</entry>
<entry>
.....
</entry>
</feed>
這就是我閱讀xml的方式。
string downloadfolder = "C:/Temp/Download/abc.xml";
XmlDocument xml = new XmlDocument();
xml.Load(downloadfolder);
XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
string xpath_title = "atom:feed/atom:entry/atom:title";
XmlNodeList nodes_title = xml.SelectNodes(xpath_title, nsmgr);
foreach (XmlNode node_title in nodes_title)
{
Console.WriteLine(node_title.InnerText);
}
string xpath_author = "atom:feed/atom:entry/atom:author";
XmlNodeList nodes_author = xml.SelectNodes(xpath_author, nsmgr);
foreach (XmlNode node_author in nodes_author)
{
Console.WriteLine(node_author.InnerText);
}
string xpath_link = "atom:feed/atom:entry/atom:link";
XmlNodeList nodes_link = xml.SelectNodes(xpath_link, nsmgr);
foreach (XmlNode node_link in nodes_link)
{
Console.WriteLine(node_link.Attributes["href"].Value);
}
我想在<entry>
節點內閱讀標題,鏈接,作者。 我正在定義xpath,然后迭代每個節點的值,是否有其他方法可以一次定義xpath,然后從<entry>
節點迭代所有值
要讀取href
屬性,您需要將xpath表達式修改為...
string xpath = "atom:feed/atom:entry/atom:link";
這將遍歷條目內的所有鏈接。 然后,您將需要讀取特定服裝的值,而不是讀取InnerText
Console.WriteLine(node.Attributes["href"].Value);
現在,如果您想閱讀entry
元素中的所有內容,xpath將很快使您的代碼有點混亂。 一種更干凈的解決方案,恕我直言,將使用xml序列化,以便您可以輕松地將“條目”解析/序列化為POCO對象。 然后,您可以使用這些對象執行任何操作
要在<entry>
節點的所有子節點上進行操作,可以在/atom:entry
停止XPath。 然后在循環中,根據需要選擇每個子節點,例如:
......
String xpath = "atom:feed/atom:entry";
XmlNodeList nodes2 = xml.SelectNodes(xpath, nsmgr);
foreach (XmlNode node in nodes2)
{
var title = node.SelectSingleNode("./atom:title", nsmgr).InnerText;
var link1 = node.SelectSingleNode("./atom:link[1]", nsmgr).Attributes["href"].Value;
//go on to select and operate on the rest child nodes
//.......
}
注意,您需要在XPath的開頭添加一個點( .
),以使XPath上下文相對於當前node
而不是整個XML文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.