Easy XPathNavigator GetAttribute

bgm*_*der 6 c# xml xpathnavigator

刚刚开始我的第一次参加XPathNavigator.

这是我的简单xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<theroot>
    <thisnode>
        <thiselement visible="true" dosomething="false"/>
        <another closed node />
    </thisnode>

</theroot>
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用该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);
    }
Run Code Online (Sandbox Code Playgroud)

问题是它无法找到属性.我已经查看了MSDN上的文档,但是无法理解正在发生的事情.

JLR*_*she 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);
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*son 6

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)