问题
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