8

I looked through a few thread here on stack overflow and I cannot find the answer. I have an xml file setup like the following:

<entry id="1" type="a">
    <name>string 1</name>
    <description>any description</description>
</entry>
<entry id="2" type="b">
    <name>string 2</name>
    <description>any description #2</description>
</entry>

I need to select all "entry" tags and return the ID, the Type, the inner name and description tags of the entry. How can I do so with C#?

Thanks,

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
MysteryDev
  • 610
  • 2
  • 12
  • 31
  • That sure looks like XML...as such, I would use XDocument and the LINQ extensions for XML. You could also use XPath if you needed the added power (at the expense of complexity, in some cases). See http://stackoverflow.com/questions/566167/query-an-xdocument-for-elements-by-name-at-any-depth – Tim M. Jan 09 '13 at 00:32
  • http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.descendants.aspx (Linq to XMl with Descendants is a good staring point). – Jason Down Jan 09 '13 at 00:34

2 Answers2

13

Keep in mind, that your xml file should have single root node. Here is parsing with Linq to Xml:

var xdoc = XDocument.Load(path_to_xml);
var entries = from e in xdoc.Descendants("entry")
              select new {
                 Id = (int)e.Attribute("id"),
                 Type = (string)e.Attribute("type"),
                 Name = (string)e.Element("name"),
                 Description = (string)e.Element("description")
              };

Query will return sequence of anonymous objects corresponding to each entry element (with properties Id, Type, Name, and Description).

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • @user1425433 [XML Documents Must Have a Root Element](http://www.w3schools.com/xml/xml_syntax.asp) in your question there is two *entry* elements on root level – Sergey Berezovskiy Jan 09 '13 at 01:17
1

Look at HtmlAgilityPack library. Using it you can parse HTML using LINQ or XPath.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125