简单的XPathNavigator GetAttribute

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的文档,但对所发生的事情无法理解。

2个回答

12

这里有两个问题:

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

谢谢!就是这样。我忽略了将节点捕获到第二个 XPathNavigator 中 - 我想我认为它的工作方式不同。我还发现了这个链接,它以简单的方式呈现了它:https://dev59.com/tG855IYBdhLWcg3wfUfQ?rq=1 - bgmCoder
@user3240414 试图通过编辑我的回答来提出以下问题(请不要这样做):语句 string thisstring = xpn.GetAttribute("visible","");Console.WriteLine(thisstring); 的输出是什么?在这种情况下,输出应该为 true - JLRishe

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接