鉴于以下XML:
<notes>
<note>
<to>Rove</to>
<from>Jan</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Joe</to>
<from>Black</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Wako</to>
<from>Halo</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Bill</to>
<from>Job</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</notes>
使用XPath和C#,如何设置以下节点:
从{fromValue}到{toValue}
从{fromValue}到{toValue}
从{fromValue}到{toValue}
从{fromValue}到{toValue}
到目前为止我尝试的内容:
const string xmlStr =
@"<notes>
<note>
......</notes>";
using (var stream = new StringReader(xmlStr))
{
var document = new XPathDocument(stream);
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/notes/note/from");
if (nodes.MoveNext())
{
XPathNavigator nodesNavigator = nodes.Current;
XPathNodeIterator nodesText =
nodesNavigator.SelectDescendants(XPathNodeType.Text, false);
while (nodesText.MoveNext())
{
var currentValue = nodesText.Current.Value;
Console.WriteLine("From: {0}, To: {1}", currentValue, currentValue);
}
}
}
我明白了:
From: Jan, To: Jan
From: Black, To: Black
...
答案 0 :(得分:2)
有许多方法可以在C#中执行您所要求的操作,而不一定涉及XPath。
最简单的想法是
foreach (var node in XDocument.Parse(xmlStr).Root.Elements("note")) {
Console.WriteLine("from: {0}; to: {1}",
node.Element("from").Value,
node.Element("to").Value);
}
这会产生输出
from: Jan; to: Rove
from: Black; to: Joe
from: Halo; to: Wako
from: Job; to: Bill
除非你被绑定到.NET 2.0(没有System.Xml.Linq
),或者有其他要求,否则我会从这开始。
答案 1 :(得分:1)
您可以使用LINQ to XML作为解决问题的优雅方式。
var document = XDocument.Parse(xml);
var xElements = document.Descendants("note");
foreach (var element in xElements)
{
Console.WriteLine(
"From {0} To {1}",
(string)element.Element("from"),
(string)element.Element("to"));
}