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″?>
<itemName>Item 1</itemName>
<itemName>Item 2</itemName>

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…


After running, the variable R would be equal to…

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…
…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…

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.