7

刚开始我第一次参加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 上的文档,但对正在发生的事情不太了解。

4

2 回答 2

11

这里有两个问题:

(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);
}
于 2013-05-04T03:12:41.507 回答
7

您可以像这样使用 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);
}
于 2016-02-13T12:04:36.827 回答