迭代并获取每个节点的ProductName和ProductId的值。什么是xpath语法。请帮忙
<Products>
<Product>
<ProductName>PDPArch</ProductName>
<ProductId>57947</ProductId>
</Product>
<Product>
<ProductName>TYFTType</ProductName>
<ProductId>94384</ProductId>
</Product>
</Products>
答案 0 :(得分:0)
while (nodes.MoveNext())
{
// here, we're on the Product node
string productName = null;
string productId = null;
// does it have child nodes?
if (nodes.Current.HasChildren)
{
// go to the first child node
bool hasMore = nodes.Current.MoveToFirstChild();
while (hasMore)
{
// extract the info
if (nodes.Current.Name == "ProductName")
{
productName = nodes.Current.Value;
}
if (nodes.Current.Name == "ProductId")
{
productId = nodes.Current.Value;
}
// does it have more children?
hasMore = nodes.Current.MoveToNext();
}
}
}
马克
<强>更新强>
更简单的方法可能是:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Your XML file name.xml");
XmlNodeList list = xmlDoc.SelectNodes("/Products/Product");
foreach(XmlNode node in list)
{
string productName = node.SelectSingleNode("ProductName").InnerText;
int productID = Convert.ToInt32(node.SelectSingleNode("ProductId").InnerText);
}
没有凌乱的XPathIterator和导航器以及所有......这适用于.NET 1.x和2.x及更高版本。
在.NET 3.5及更高版本中,您还可以使用Linq-to-XML更轻松地解析XML。