在 XML 中选择节点 [英] Selecting nodes in XML
本文介绍了在 XML 中选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 c# 中使用 xpath 选择节点
I'm trying to select nodes using xpath in c#
这是我的 XML 文件
This is my XML file
<?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>
到目前为止,这是我的错误代码:
This is my incorrect code so far:
// 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);
}
我想像这样从item"输出title":
What I want to output the "title" from "item" like this:
This title
The other title
如果你知道怎么做,请告诉我
Please let me know if you know how to do this
推荐答案
我建议你使用 Linq to Xml:
var xdoc = XDocument.Load("file.xml");
var titles = from i in xdoc.Root.Element("channel").Elements("item")
select (string)i.Element("title");
或者使用 XPath:
Or with XPath:
var titles = xdoc.XPathSelectElements("rss/channel/item/title")
.Select(t => (string)t);
返回带有标题的 IEnumerable
.
foreach (string title in titles)
Console.WriteLine("Title: {0}", title); // note item placeholder in format
这篇关于在 XML 中选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文