Parsing XML with C#

This has to be quick because I have things to do and this tangent, although a good teaching lesson to myself, has to wrap up so I can get back to the grind.

To me XML should be simple but gets all complicated with namespaces, XSD, XSLT, etc…  I’m kind of like a detective and want “Just the facts DATA ma’am”.  Secondly, I’ve never really seen the purpose of LINQ and usually just use datatables as they are simple and easy to use.  However, when you are given lemons XML, you make lemonade LINQ queries.  It will save you some frustration.

So if you have this XML…

<?xml version=”1.0″?>
<items>
<item>
<itemName>Item 1</itemName>
</item>
<item>
<itemName>Item 2</itemName>
</item>
</items>

You can select different elements using LINQ to XML.  Name you use XElement.  Do not confuse XElement with XmlDocument.  XmlDocument is older and will only serve to confuse you.

To select all the itemName’s and add them to a string you would…

image

After running, the variable R would be equal to…
C# LINQ XML RESULTS

This above Linq says [Select all elements from XE’s descendants that are named “itemName”].  It’s very reminiscent of a SQL statement.

Then we piece together a string called “R” that adds the value of each element to itself.

Now you know the basics.  You can iterate differently in your “foreach” statement.  You don’t have to use el.Value.  You could find different sub-elements if they existed, load it into a class or do whatever but there is one more thing that got me when I first learned.  That is “xmlns”.

So if this line…
<item>
…was replaced with this line
<items xmlns=”http://SomeWebsite/Version1.0″>
Then your code wouldn’t work.

The code wouldn’t work because even though <itemName> still looks like “<itemName” in the file, it is not.

Now this may seem confusing because if you open the XML file you will see <itemName> all over the place.  However, because you added an XML Namespace (ie. xmlns=”http://SomeWebsite/Version1.0”) LINQ now considers the name to be…
LINQ XMLNS Fixed

This may seem like it’s an over complication when you just want the data, however when there are different versions of elements this kind of versioning saves headaches down the road.

Hopefully this simplifies things for you.  It would have saved me some Googling if I would have found something similar earlier.

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 6 = fifteen

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>