我正在尝试在C#中使用xpath选择节点
这是我的XML文件
<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>Some other title</title>
<item>
<description><![CDATA[<img src="http://www.site.com/image.jps"/><br />]]></description>
</item>
<item>
<title>This title</title>
<subtitle><subtitle>
<Date>Fri, 21 Mar 2014 08:30:44 GMT</Date>
<description>Some description</description>
</item>
<item>
<title>The other title</title>
<subtitle><subtitle>
<Date>Fri, 21 Mar 2014 08:30:44 GMT</Date>
<description>The other description</description>
</item>
</channel>
</rss>
到目前为止,这是我的错误代码:
// Load the document and set the root element.
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
// Select nodes
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("/channel/item/");
foreach (XmlNode xn in nodeList)
{
string fieldLine = xn["Title"].InnerText;
Console.WriteLine("Title: ", fieldLine);
}
我想从“项目”输出“标题”,如下所示:
This title
The other title
如果您知道该怎么做,请告诉我
我建议您使用Linq到Xml:
var xdoc = XDocument.Load("file.xml");
var titles = from i in xdoc.Root.Element("channel").Elements("item")
select (string)i.Element("title");
或使用XPath:
var titles = xdoc.XPathSelectElements("rss/channel/item/title")
.Select(t => (string)t);
返回IEnumerable<string>
标题。
foreach (string title in titles)
Console.WriteLine("Title: {0}", title); // note item placeholder in format
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句