我有以下代码,可用于遍历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”。这就是我确定其正确节点的方式),如果是,则获取其子节点。
有人可以帮我从这里出去吗?我对XML很陌生。谢谢是前进!
最佳答案
假设您的XML具有以下结构:
<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查询,请参阅此link。
UPDATE :
如果要选择文档中所有具有
X
属性的元素。不管它们存在于何处。您可以使用以下命令://select all elements in the doucment having attribute X
XmlNodeList nodeList = root.SelectNodes("//*[@X]");
关于c# - 使用XmlDocument进行XML遍历,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24378810/