Nicke Manarin
Nicke Manarin

Reputation: 3358

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?

Upvotes: 1

Views: 1342

Answers (2)

BLoB
BLoB

Reputation: 9725

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.

Upvotes: 1

Steve B
Steve B

Reputation: 37690

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")
{
  //...
}

Upvotes: 2

Related Questions