刚刚开始我的第一次拍摄XPathNavigator
。
这是我的简单xml:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<theroot>
<thisnode>
<thiselement visible="true" dosomething="false"/>
<another closed node />
</thisnode>
</theroot>
现在,我正在使用CommonLibrary.NET
库来帮助我一点:
public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);
const string thexpath = "/theroot/thisnode";
public static void test() {
XPathNavigator xpn = theXML.CreateNavigator();
xpn.Select(thexpath);
string thisstring = xpn.GetAttribute("visible","");
System.Windows.Forms.MessageBox.Show(thisstring);
}
问题是它无法找到属性。我已经查看了MSDN上的文档,但是对于发生的事情无法理解。
答案 0 :(得分:7)
这里有两个问题:
(1)您的路径是选择thisnode
元素,但thiselement
元素是具有属性的元素
(2).Select()
不会更改XPathNavigator
的位置。它返回带有匹配项的XPathNodeIterator
。
试试这个:
public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);
const string thexpath = "/theroot/thisnode/thiselement";
public static void test() {
XPathNavigator xpn = theXML.CreateNavigator();
XPathNavigator thisEl = xpn.SelectSingleNode(thexpath);
string thisstring = xpn.GetAttribute("visible","");
System.Windows.Forms.MessageBox.Show(thisstring);
}
答案 1 :(得分:5)
你可以使用像这样的xpath选择元素的属性(上面接受的答案的替代方法):
public static XmlDocument theXML = XmlUtils.LoadXMLFromFile(PathToXMLFile);
const string thexpath = "/theroot/thisnode/thiselement/@visible";
public static void test() {
XPathNavigator xpn = theXML.CreateNavigator();
XPathNavigator thisAttrib = xpn.SelectSingleNode(thexpath);
string thisstring = thisAttrib.Value;
System.Windows.Forms.MessageBox.Show(thisstring);
}