1

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?

1
  • new XmlTextReader() has been deprecated since .NET 2.0. You should be using XmlReader.Create() instead. Depending on what else you're doing with the XML, you'll find LINQ to XML much easier than playing with XmlReaders. Commented May 20, 2013 at 17:58

2 Answers 2

2

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")
{
  //...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.