str1和str2是字符串变量,它保存要访问的节点的值,在这种情况下str1 =“abc”和str2 =“efg”。变量x是一个整数,当我运行我的程序时,我得到一个“值太大或太小而不能用于int32”错误:
XPathDocument xmlDoc = new XPathDocument(path);
XPathNavigator course= xmlDoc.CreateNavigator();
XPathNodeIterator value = course.Select("/root/x[@atr =" + str1 + "]/y[@atr =" + str2 + "]/value1");
x = Convert.ToInt32(value.Current.Value);
我的xml是:
<root>
<x atr = "abc">
<y atr ="efg">
<value1>12</value1>
<value2>25</value2>
<value3>16</value3>
</y>
</x>
</root>
答案 0 :(得分:3)
编辑:这是一个简单的例子:"/root/x[@atr ='" + str1 + "']/y[@atr ='" + str2 + "']/value1"
你需要在路径中的属性字符串周围引用。
你的构建x /root/x[@atr=abc]/y[@atr=efg]/value1
这个构建/root/x[@atr='abc']/y[@atr='efg']/value1
与大多数语言一样,字符串也需要在xpath中引用它们。
原始代码的问题在于XPathNodeIterator
,您需要在致电value.MoveNext();
之前致电value.Current
XPathNodeIterator value = course.Select("/root/x/y/value1");
value.MoveNext();
x = Convert.ToInt32(value.Current.Value);
我正在使用的完整示例代码:
var doc = XDocument.Parse(@"<root>
<x>
<y>
<value1>12</value1>
<value2>25</value2>
<value3>16</value3>
</y>
</x>
</root>");
////Also works for XmlDocument
//XmlDocument doc = new XmlDocument();
//doc.LoadXml(@"<root>
// <x>
// <y>
// <value1>12</value1>
// <value2>25</value2>
// <value3>16</value3>
// </y>
// </x>
//</root>");
XPathNavigator course = doc.CreateNavigator();
XPathNodeIterator value = course.Select("/root/x/y/value1");
Console.WriteLine(value.Current.Value); //Outputs 122516, which is the same as doc.Root.Value or XmlDocument.InnerText
value.MoveNext();
Console.WriteLine(value.Current.Value); //Outputs 12, correctly
int x = Convert.ToInt32(value.Current.Value); //Parses fine
答案 1 :(得分:1)
我只想使用XDocument的扩展方法XPathSelectElement,如下例所示:
var doc = XDocument.Parse(@"<root>
<x atr = 'abc'>
<y atr = 'efg'>
<value1>12</value1>
<value2>25</value2>
<value3>16</value3>
</y>
</x>
</root>");
var x = int.Parse(doc.XPathSelectElement("/root/x[@atr =\"abc\"]/y[@atr = \"efg\"]/value1").Value);
Console.WriteLine(x);