2013-05-04 62 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); 
}