2014-02-28 81 views
0

我需要閱讀sintal ID A和西爾維亞C#讀取XML 5層深

<?xml version="1.0" encoding="ISO-8859-1"?> 
<kdd> 
    <Table> 
     <robel ID="1"> 
      <groof NAME="GOBS-1"> 
       <sintal ID="A">Sylvia</sintal> 
      </groof> 
     </robel> 
    </Table> 
</kdd> 

下面我試圖和它沒有工作。元素的值爲null,之後退出。

XDocument doc = XDocument.Load("myname.xml"); 
foreach (XElement element in doc.Descendants("sintal")) 
{ 
    string my_id = element.Attribute("sintal").Value; 
} 
+0

它以什麼方式不起作用? –

+0

您應該只能使用元素的XPath。 (如果您知道文檔結構,則無需循環) –

回答

4

您的屬性名稱不IDsintalsintal是你元素名。試試這個:

string my_id = (string)element.Attribute("ID"); 
string myValue = (string)element; 

還可以使用明確投而不是Value屬性來獲取元素的值或attribute.It避免NullReferenceException