使用XmlDocument进行XML遍历 [英] XML traversing using XmlDocument
问题描述
我有以下代码,可用于遍历XML:
I have the following code, which I use to traverse the XML:
private void btn_readXML_Click(object sender, EventArgs e)
{
var doc = new XmlDocument();
doc.Load("e:\\contacts.xml");
// Load xml document.
TraverseNodes(doc.ChildNodes);
}
static List<string> xmlnodes = new List<string>();
private static void TraverseNodes(XmlNodeList nodes)
{
foreach (XmlNode node in nodes)
{
List<string> temp = new List<string>();
temp.Add("Node name: " + node.Name.ToString());
XmlAttributeCollection xmlAttributes = node.Attributes;
foreach (XmlAttribute at in xmlAttributes)
{
temp.Add(" Atrib: " + at.Name + ": " + at.Value);
}
xmlnodes.AddRange(temp);
TraverseNodes(node.ChildNodes);
}
但是我的问题是,我不想遍历整个文档,我只想遍历具有属性 X的节点及其子节点。请注意,我不知道该节点在哪里。因此,基本上,我要做的就是找出节点是否存在(其属性为 X。这就是我确定其正确节点的方式),如果是,则获取其子节点。
But my problem is, I don't want to traverse the whole document, I only want to traverse the node and subsequently its children which has an attribute 'X'. Please note that I don't know where the node is present. So basically what I have to do is, find out if the node exists ( it'll have the attribute 'X'. That's how I identify its the right node) if yes then fetch its children.
有人可以帮我吗?我刚接触XML。
Can anyone help me out here? I'm pretty new to XMLs. Thanks is advance!
推荐答案
假设您的XML具有以下结构:
Assuming your XML having following structure:
<Contacts>
<Contact X="abc">
<Child1></Child1>
</Contact>
<Contact X="def">
<Child2></Child2>
</Contact>
</Contacts>
使用 XmlNode.SelectNodes :
var doc = new XmlDocument();
doc.Load("e:\\contacts.xml");
//get root element of document
XmlElement root = doc.DocumentElement;
//select all contact element having attribute X
XmlNodeList nodeList = root.SelectNodes("//Contact[@X]");
//loop through the nodelist
foreach (XmlNode xNode in nodeList)
{
//traverse all childs of the node
}
有关其他 XPath查询,请参见此链接。
更新:
如果要选择文档中所有具有属性 X
的元素。不管它们存在于何处。您可以使用以下命令:
If you want to select all elements having attribute X
in the document. No matters where they exists. You could use following:
//select all elements in the doucment having attribute X
XmlNodeList nodeList = root.SelectNodes("//*[@X]");
这篇关于使用XmlDocument进行XML遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!