读取xml节点属性 [英] Read xml node attribute
问题描述
我有一个具有这样的节点的xml文档,< ITEM id ="1" name ="bleh" .../>
我要做的是获取文档中存在的每个ITEM节点的所有id的属性值.
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.
我已经尝试过这种方法,但是没有用:
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);
}
推荐答案
您应使用 XmlNamespaceManager 在对 SelectSingleNode()的调用中a>,因为您的XML确实包含一个名称空间:
You should use XmlNamespaceManager in your call to SelectSingleNode() since your XML does contain a namespace on it:
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.
我的代码与您的代码的不同之处在于,我使用的是//
,因此不是从文档的开头开始,而是双斜杠//
表示: XPath
评估程序,以查看XML文档中的任何地方.
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 XPath
evaluator to look anywhere in an XML document.
这是我的 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>
这是我的阅读方式:
var doc = new XmlDocument();
doc.Load("example.xml");
foreach (XmlNode node in doc.SelectNodes("//ITEM[@id]"))
{
Console.WriteLine(node.Attributes["id"].Value);
}
使用单斜杠,上面的 XPath
看起来像这样:
With single slash, the above XPath
would look like this:
/root/items/ITEM
我也在使用 [@ id]
来确保 ITEM
元素具有 ID
属性,但这不是必需的,如果您知道它们都有一个 ID
属性.
I am also using [@id]
to ensure that the ITEM
element have an ID
attribute but that is not necessary if you know they all have an ID
attribute.
这篇关于读取xml节点属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!