Parsing XML Content in C# – Possible Errors And Walkthrough

Often we deal with XML content/files in our projects, for read/write/parse/save/delete etc.. operations.

The two classes that will come handy in this case are XDocument and XmlDocument.

XDocument is what we know as the extended version of XmlDocument which was the standard DOM-Style API for XML whereas the former is the LINQ to XML API.

I would rather suggest you use XDocument which was unleashed in ASP.Net 3.5
And if you are using ASP.Net 3.0 or less you are bound to use XmlDocument.

Lets say we have a XML file in your project directory test_file.xml having something like this




 
where xmlns is the namespace and you want to add a new element.

XDocument document = XDocument.Load(“text_file.xml”); var xElement = document.Root; // – – gives you the root node after which you want to add an element. xElement.Add(new XElement(“elementName”, “testElement”)); //– Adds just after the last element of root.

document.Save(“text_file.xml”);

This will result in




testElement

If you want to create an Element without any element specific namespace(xmlns) attribute , you need to use

xElement.Add(new XElement(xElement.Name.Namespace + "elementName", "testElement"));

This will result in

testElement

Why this is required.?
When we are using xslt transformation to fetch an element value from xml, you generally use the following syntax

It will throw error if namespace is null. In order to overcome this you qtr required to use xmlns while adding a new element.
And yes, I had tried with attribute.Remove(), to remove xmlns attribute which didn’t work eventually.

There might be another situation where we are calling a service to get the XML content and not loading a XML file from our project directory. Lets say something like this

var result = someservice that returns XML content as string.

So if we use

XDocument document = XDocument.Load(result);

The likely error we will be getting is “XML Illegal Characters in path”

WHY ?
Because XDocument.Load method expects a filename and not an actual xml string.

To overcome this you need to use XDocument.Parse(result)
OR

XmlDocument.LoadXml(result)

So Load and Parse needs to be used wisely.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!