Skip to main content
 首页 » 编程设计

c#之选择 XML 中的节点

2024年02月13日10lyhabc

我正在尝试在 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 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:

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