Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parsing XML File

Tags:

c#

xml

linq

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,

like image 271
MysteryDev Avatar asked Jan 09 '13 00:01

MysteryDev


2 Answers

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).

like image 51
Sergey Berezovskiy Avatar answered Oct 05 '22 08:10

Sergey Berezovskiy


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

like image 22
Kirill Polishchuk Avatar answered Oct 05 '22 08:10

Kirill Polishchuk