Search code examples
c#xmlxml-namespacesxmlreader

Query issue on XmlReader with namespace alias/prefix


Trying to query XML with C# trough XmlReader but gets error cause namespace alias. The XML file is very large (<1,6GB) and alias and namespace can vary from file to file.

In the example below Im trying find the "MsgHead" tag but since there are a alias (<*mh:*MsgHead>) the query do not detect the tag. Since namespace and alias vary its not option to hard code alias and namespace.

Is there any option to ignore namespace alias?

XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<mh:MsgHead xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        xmlns:mh="http://www.kith.no/xmlstds/msghead/2006-05-24"
        xmlns:n1="http://www.altova.com/samplexml/other-namespace"
        xsi:schemaLocation="http://www.kith.no/xmlstds/msghead/2006-05-24 MsgHead-v1_2.xsd">
 <mh:MsgInfo>
  <mh:Type DN="xxx" V="xxx"/>
  <mh:MIGversion>v1.2 2006-05-24</mh:MIGversion>
  <mh:GenDate>2014-04-01T20:53:08</mh:GenDate>
  <mh:MsgId>xxx</mh:MsgId>
  <mh:ProcessingStatus DN="Produksjon" V="P"/>
  <mh:RequestedPriority DN="Normal" V="N"/>
  <mh:Ack DN="Ja" V="J"/>
  <mh:Sender>
   <mh:ComMethod DN="EDI" V="EDI"/>
   <mh:Organisation>
<mh:OrganisationName>xxxx</mh:OrganisationName>
<mh:Ident>
 <mh:Id>69</mh:Id>
 <mh:TypeId S="xxx" DN="HER-id" V="HER"/>

C# code:

string meldingsType = "N/A";
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
XmlReader xmlLeser = XmlReader.Create(fil, settings);
while (xmlLeser.Read())
{
    if ((xmlLeser.NodeType == XmlNodeType.Element) && (xmlLeser.Name == "MsgHead"))
    {
       meldingsType = "Hodemelding";
       break;
    }

Solution

  • Don't check for a certain namespace prefix. The prefix doesn't matter, what matters are the local name and the namespace URI of the element.