2

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;
    }
kaareol
  • 23
  • 4
  • Why are you using such a low-level tool as `XmlReader`? Have you tried LINQ to XML? – John Saunders Apr 09 '14 at 07:11
  • Since the file are very large and XmlReader is not loading the file to memory. But no I have not tried LINQ to XML mainly becouse Im not familiar with LINQ. – kaareol Apr 09 '14 at 07:14
  • You should become familiar with LINQ to XML. `XNamespace mh = "http://www.kith.no/xmlstds/msghead/2006-05-24"; var msgHead = doc.Element(mh+"MsgHead");` – John Saunders Apr 09 '14 at 08:23
  • The problem with the prefix/alias is that it could be something totaly different on the next xml file, the same with the namespace. – kaareol Apr 09 '14 at 09:45
  • The _namespace_ could be different? Then how are you expected to read the document? – John Saunders Apr 09 '14 at 13:43

1 Answers1

2

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.

jasso
  • 13,736
  • 2
  • 36
  • 50
  • Thats correct. I change .Name to .LocalName and the problem is solved. Check also link: http://stackoverflow.com/questions/15139979/select-node-without-namespace-with-xpath – kaareol Apr 11 '14 at 08:59