How to get XML namespace?

家住魔仙堡 提交于 2020-01-06 02:20:28

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/16652624/how-to-get-xml-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!