<OrderItems>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
<OrderItem>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
<OrderItem>
</OrderItems>
有上面一段XML内容,请问如何读取所有ProductID节点(读取某个指定节点)的值?
string xml =
@"<OrderItems>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
</OrderItem>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
</OrderItem>
</OrderItems>";
XDocument doc = XDocument.Parse(xml);
var nodes = doc.Descendants("ProductID");
foreach (var node in nodes)
{
Console.WriteLine(node.Value);
}
这是.net 3.5的XLINQ写法
string xml =
@"<OrderItems>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
</OrderItem>
<OrderItem>
<ID>1</ID>
<ProductID>6</ProductID>
<PrdductName>联想笔记本电脑</PrdductName>
<Quantity>100</Quantity>
</OrderItem>
</OrderItems>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList nodes = doc.GetElementsByTagName("ProductID");
for (int i = 0; i < nodes.Count; i++)
{
XmlNode node = nodes[i];
Console.WriteLine(node.InnerText);
}
这是.net 2.0标准XML API的写法