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
I suggest you to use Linq to Xml:
Or with XPath:
That returns
IEnumerable<string>
with titles.You are just missing the full path from the
rss
root:(Since not all
<item>
s have titles, exclude ones which do not). Also, note thatxml
is case sensitive: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: