Selecting nodes in XML

2020-07-30 03:27发布

问题:

I'm trying to select nodes using xpath in c#

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);
            }

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

回答1:

I suggest you to use 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");

Or with XPath:

var titles = xdoc.XPathSelectElements("rss/channel/item/title")
                 .Select(t => (string)t);

That returns IEnumerable<string> with titles.

foreach (string title in titles)
    Console.WriteLine("Title: {0}", title); // note item placeholder in format


回答2:

You are just missing the full path from the rss root:

XmlNodeList nodeList = root.SelectNodes("/rss/channel/item[title]/");
foreach(...)

(Since not all <item>s have titles, exclude ones which do not). Also, note that xml is case sensitive:

string fieldLine = xn["title"].InnerText;


回答3:

Please consider the below points, and you will get the required output..

1)Subtitle in your posted question is missing end tags, Please put'/' in End tag

2) You were very close to the right code, please replace it with:

        XmlDocument doc = new XmlDocument();
        doc.Load("file.xml");

        XmlNodeList nodeList = doc.SelectNodes("rss/channel/item/title");

        foreach (XmlNode xn in nodeList)
        {
            Console.WriteLine("Title: {0}", xn.InnerText);
        }


标签: c# xml xpath