2

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

2
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. Commented Mar 16, 2014 at 14:51
  • subtitle elements are not closed in your xml. I believe its just a typo Commented Mar 16, 2014 at 14:56

3 Answers 3

3

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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; 

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.