简体   繁体   中英

How to get XML namespace?

I tried using this code: [C#]

var textReader = new XmlTextReader(path);
if (textReader.NamespaceURI == "http://www.portalfiscal.inf.br/nfe")
{
  //...
}

My XML:

<?xml version="1.0" encoding="utf-8"?>
<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
<infNFe version="2.00" Id="NFe31130317194994450127550012302143751002144567">
<ide>
//continue...

But my code always returns "" ...

Is there a easy way to get XML namespace?

Your code will return the namespaceUri of the current node.

Try to advance in the xml stream:

var textReader = new XmlTextReader(path);
while(reader.NodeType != XmlNodeType.Element) textReader.Read();
if (textReader.NamespaceURI == "http://www.portalfiscal.inf.br/nfe")
{
  //...
}

Here's a nice linq method:

XDocument z = XDocument.Parse(s);
var result = z.Root.Attributes().
    Where(a => a.IsNamespaceDeclaration).
    GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
            a => XNamespace.Get(a.Value)).
    ToDictionary(g => g.Key, 
                 g => g.First());

Find this method and more at hanselmans site: Get namespaces from an XML Document with XPathDocument and LINQ to XML

Then just loop through the dictionary as desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM