2012-05-07 22 views
0

這裏是我的xml文件如何讓XML的.text使用C#

<TEST> 
    <Project_Name>browser</Project_Name> 

     <Setting BrowserKind ="Firefox" ></Setting> 

     <ExecuteUrl>http://yahoo.com</ExecuteUrl> 

    <caseBox>  
    <test1>apple</test1> 
    </caseBox> 
</TEST> 

這個XML意味着什麼,這是一個例子。我只是想做一些練習。

這裏有3件事我想:

(1)火狐

(2)http://yahoo.com

(3)蘋果

我使用的XmlDocument ,但失敗了,沒有我完全得到。

我怎樣才能得到它們?

謝謝。

這是我的測試,以獲取Firefox

這裏是我的代碼:

 XmlDocument XmlDoc = new XmlDocument(); 
     XmlDoc.Load(here I PLACE THE LOCATION OF FILE); 
     XmlNodeList NodeLists = XmlDoc.SelectNodes("TEST/Setting"); 


     foreach (XmlNode OneNode in NodeLists) 
     { 

      String StrAttrValue1 = OneNode.Attributes[" Browserkind "].Value; 
      String StrAttrValue2 = OneNode.InnerText; 
     } 
+2

你提到你使用XmlDocument失敗,但沒有顯示你是如何使用它。所以我們有點難以告訴你你嘗試失敗的原因。 –

+0

你從哪裏失敗? – V4Vendetta

+0

我發佈了代碼。調試顯示字符串2都爲空。 – Edison

回答

0

如果切換到LINQ到XML是一種選擇,而不是早期的XML API,我會做到這一點。

var doc = XDocument.Parse(@"<TEST> 
    <Project_Name>browser</Project_Name> 

     <Setting BrowserKind =""Firefox"" ></Setting> 

     <ExecuteUrl>http://yahoo.com</ExecuteUrl> 

    <caseBox>  
    <test1>apple</test1> 
    </caseBox> 
</TEST>"); 


var result = (from test in doc.Elements("TEST") 
       select new { BrowserKind = test.Element("Setting").Attribute("BrowserKind").Value, 
          ExecuteUrl = test.Element("ExecuteUrl").Value, 
          CaseBox = test.Element("caseBox").Element("test1").Value }); 
+0

哇,謝謝你。但我不能在參考中找到system.xml.linq?爲什麼? – Edison

+0

您的項目是否針對.NET 3.5或更高版本?程序集System.Xml.Linq在3.5中添加。如果您使用的是3.5或更高版本,則只需轉到添加引用並添加System.Xml.Linq,然後在代碼中添加'using System.Xml.Linq;'。 – HackedByChinese

+0

好的非常感謝你! – Edison

0

Xml區分大小寫,所以要得到一個BrowserKind屬性,「browserkind」將不起作用。它必須完全匹配名稱。

與XML文檔試試這個:

String apple = doc.DocumentElement["caseBox"]["test1"].InnerText;

0

似乎有多餘的空格,當你寫屬性名稱「Browserkind」 ..嘗試將其刪除。我希望它可以幫助