我刚开始使用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上的文档,但是对发生的事情并不太了解。

最佳答案

这里有两个问题:

(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);
}

关于c# - 简单的XPathNavigator GetAttribute,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16370183/

10-12 07:16