Search code examples
c#xmlxml-namespacesxmlreader

Process namespaces using XmlReader


I have a complex XML file with structure as follows:

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="xxx:xxx:xxx:xxx:xxxxx:xxx:xsd:xxxx.xxx.xxx.xx">
    <Element1>
        <Element2>
            <Element2A>xxxxxx</Element2A>
            <Element2B>2012-08-29T00:00:00</Element2B>
        </Element2>
    </Element1>
</Document>

Now I am using XmlReader to read this XML document and process information as follows

XmlReader xr = XmlReader.Create(filename);
while (xr.Read()) 
{
   xr.MoveToElement();
   XElement node = (XElement)XElement.ReadFrom(xr);
   Console.WriteLine(node.Name);
}
xr.Close();

The problem I am facing is in the output the namespace is prefixed to the ElementName. E.g output

{xxx:xxx:xxx:xxx:xxxxx:xxx:xsd:xxxx.xxx.xxx.xx}Element1

Is there any way I can remove/ handle this as I need to do further filtering using Element names and Child names.


Solution

  • XElement.Name is not (as you might expect) a String, but rather an XName which has a LocalName property, thus:

    Console.WriteLine(node.Name.LocalName);