C# 读取xml节点属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18818618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:17:37  来源:igfitidea点击:

Read xml node attribute

c#xmlvisual-studio-2012

提问by Derezzed

I have an xml document that have nodes like this, <ITEM id="1" name="bleh"... />What I want to do is get all id's attribute value for each ITEM node that exists in the document.

我有一个 xml 文档,它有这样的节点,<ITEM id="1" name="bleh"... />我想要做的是获取文档中存在的每个 ITEM 节点的所有 id 属性值。

So, how can I do that?

那么,我该怎么做呢?

Edit: I've tried this way and it didn't works:

编辑:我试过这种方式,但没有奏效:

XmlDocument Doc = new XmlDocument();
        Doc.Load("example.xml");
        XmlNodeList nodeList = Doc.SelectNodes("/ITEM");
        foreach (XmlNode node in nodeList)
        {
            string id = node.Attributes["id"].Value;
            Console.WriteLine(id);
        }

采纳答案by Prix

You should use XmlNamespaceManagerin your call to SelectSingleNode()since your XML does contain a namespace on it:

您应该在对SelectSingleNode() 的调用中使用XmlNamespaceManager,因为您的 XML 确实包含一个命名空间:

var doc = new XmlDocument();
doc.Load("example.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("anyname", "http://tempuri.org/zitem.xsd");
foreach (XmlNode node in doc.SelectNodes("//anyname:ITEM", ns))
{
    Console.WriteLine(node.Attributes["id"].Value);
}

That's why you get no result.

这就是为什么你没有结果。

The difference from my code to yours is that I am using //so instead of starting at the root of a document, a double forward slash //indicates to an XPathevaluator to look anywhere in an XML document.

我的代码与您的代码的不同之处在于我使用的是//so 而不是从文档的根开始,双正斜杠//指示XPath评估器查看 XML 文档中的任何位置。

Here is my example.xmlas sample:

这是我的example.xml示例:

<root>
  <items>
    <ITEM id="1" name="bleh=" />
    <ITEM id="2" name="bleh=" />
    <ITEM id="3" name="bleh=" />
    <ITEM id="4" name="bleh=" />
    <ITEM id="5" name="bleh=" />
    <ITEM id="6" name="bleh=" />
    <ITEM id="7" name="bleh=" />
    <ITEM id="8" name="bleh=" />
  </items>
</root>

And here is how I am reading it:

这是我阅读它的方式:

var doc = new XmlDocument();
doc.Load("example.xml");
foreach (XmlNode node in doc.SelectNodes("//ITEM[@id]"))
{
    Console.WriteLine(node.Attributes["id"].Value);
}

With single slash, the above XPathwould look like this:

使用单斜杠,上面XPath看起来像这样:

/root/items/ITEM

I am also using [@id]to ensure that the ITEMelement have an IDattribute but that is not necessary if you know they all have an IDattribute.

我还[@id]用于确保ITEM元素具有ID属性,但如果您知道它们都具有ID属性,则没有必要这样做。