2013-05-04 65 views
3

刚刚从这里开始,我的第一份作品是XPathNavigator简单的XPathNavigator GetAttribute

这是我简单的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

两个问题:

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

谢谢!而已。我忽略了将节点捕获到第二个'XPathNavigator'中 - 我想我认为它的工作方式不同。我也发现这个链接,它也以一种简单的方式呈现它:http://stackoverflow.com/questions/4308118/c-sharp-get-attribute-values-from-matching-xml-nodes-using-xpath-query ?rq = 1 – bgmCoder 2013-05-04 03:15:45

+0

@ user3240414试图通过编辑我的答案来询问以下问题(请不要这样做):_什么是语句输出'string thisstring = xpn.GetAttribute(“visible”,“”); Console.WriteLine(thisstring);'_在这种情况下,输出应该是'true'。 – JLRishe 2014-01-29 14:03:12

3

您可以使用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); 
}