首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Easy XPathNavigator GetAttribute

Easy XPathNavigator GetAttribute
EN

Stack Overflow用户
提问于 2013-05-04 11:05:57
回答 2查看 17.2K关注 0票数 7

这只是我在XPathNavigator的第一次拍摄的开始。

这是我的简单xml:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<theroot>
    <thisnode>
        <thiselement visible="true" dosomething="false"/>
        <another closed node />
    </thisnode>

</theroot>

现在,我使用CommonLibrary.NET库来帮我一点忙:

代码语言:javascript
运行
复制
    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上的文档,但无法理解发生了什么。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-04 11:12:42

这里有两个问题:

(1)您的路径是选择thisnode元素,但thiselement元素具有和属性

(2) .Select()不改变XPathNavigator的位置。它返回一个包含匹配项的XPathNodeIterator

试试这个:

代码语言:javascript
运行
复制
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);
}
票数 11
EN

Stack Overflow用户

发布于 2016-02-13 20:04:37

您可以像这样使用xpath在元素上选择属性(这是上面接受的答案的另一种选择):

代码语言:javascript
运行
复制
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);
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16370183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档