简体   繁体   English

如何获取XML命名空间?

[英]How to get XML namespace?

I tried using this code: [C#] 我尝试使用这段代码:[C#]

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

My XML: 我的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? 有没有简单的方法来获取XML命名空间?

Your code will return the namespaceUri of the current node. 您的代码将返回当前节点的namespaceUri。

Try to advance in the xml stream: 尝试在xml流中前进:

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: 这是一个很好的linq方法:

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 hanselmans站点上找到此方法及更多内容:使用XPathDocument和LINQ to XML从XML文档中获取名称空间

Then just loop through the dictionary as desired. 然后根据需要循环遍历字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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