Ploetzeneder
Ploetzeneder

Reputation: 1331

XML parsing in C#

How can I Parse this XML

<?xml version="1.0" encoding="utf-8"?>
<RESULT imgURL="www.diedomain.de/images/request_12345.jpg">
<ITEM name="test AG" status="nicht betroffen" />
<ITEM name="test3 GmbH" status="betroffen" />
<ITEM name="versuchs GmbH" status="nicht betroffen" />
<ITEM name="bergwerk GmbH" status="betroffen" />
</RESULT>

in C# easiest? I want to get all items in an List and imgurl too? Can you show me an method for this one? i tried serializer, but did not work.

This also did not work:

XDocument doc = XDocument.Parse("<?xml version=\"1.0\" encoding=\"utf-8\"?><RESULT imgURL=\"www.diedomain.de/images/request_12345.jpg\"><ITEM name=\"test AG\" status=\"nicht betroffen\" /><ITEM name=\"test3 GmbH\" status=\"betroffen\" /><ITEM name=\"versuchs GmbH\" status=\"nicht betroffen\" /><ITEM name=\"bergwerk GmbH\" status=\"betroffen\" /></RESULT>");
List<XElement> items = doc.Descendants("ITEM");
string imgurl = doc.Element("RESULT").Attribute("imgURL").Value;

Upvotes: 0

Views: 195

Answers (5)

Pete Stens&#248;nes
Pete Stens&#248;nes

Reputation: 5675

There is also the option of running XSD.exe (from the VS command line) to get it to generate a CLR class with the apropriate attributes to serialise to/from the XML format you give (with the XmlSerializer class).

You can also do this by hand, but XSD will do the hard work for you.

Upvotes: 0

Reinderien
Reinderien

Reputation: 15263

I would suggest using plain old XmlSerializer on an annotated class that you write, RESULT. RESULT would have an imgURL string attribute and a List<> of ITEMs.

Upvotes: 0

Brian Driscoll
Brian Driscoll

Reputation: 19635

You'll have to replace myXml with a valid URI reference to the XML that you want to parse.

XDocument doc = new XDocument(myXml);
List<XElement> items = doc.Descendants("ITEM");
string imgurl = doc.Element("RESULT").Attribute("imgURL").Value;

Upvotes: 1

czuroski
czuroski

Reputation: 4332

Look at using linq to xml - http://msdn.microsoft.com/en-us/library/bb387098.aspx

Upvotes: 0

Grook
Grook

Reputation: 405

IMHO LINGQ to SXML is the best choise. Tehere are a lot of examples here

Upvotes: 0

Related Questions