2014-01-28 122 views
0

空節點使用LINQ to XML,我想獲得的屬性值:從「媒體」,「NAME 1和NAME」節點:從節點獲取屬性值,並檢查使用LINQ to XML

<server> 
<networkAdapters> 
</networkAdapters>  
<media name1="test1" name2="test2"> 
    <groups> 
     <group name="Group Name"> 
    </groups> 
    <others> 
    </others> 
</media> 
</server> 

The code should also check for null or non existent nodes at all, for instance: 

<server> 
<networkAdapters> 
</networkAdapters>  
<media> 
    <groups> 
    </groups> 
    <others> 
    </others> 
</media> 
</server> 

or 

<server> 
<networkAdapters> 
</networkAdapters> 
</server> 

我是相當新的LINQ到XML和我嘗試以下操作:

string attribute1 = doc.Descendants("media").Select(s => s.Attribute("name1")).ToString(); 
string attribute2 = doc.Descendants("media").Select(s => s.Attribute("name2")).ToString(); 

我知道是完全錯誤的,但它是一個開始。歡迎任何幫助。 謝謝!

回答

0
var name1 = (string)(xDoc.Root.Element("media") ?? New XElement("media")).Attribute("name1"); 
+0

工作完美,謝謝! – Max