2014-08-27 100 views
-3

我有一個是格式化這樣的.XML:讀取XML節點在C#

<!--List of Locations--> 
<Locations> 
    <Location Name="House"> 
     <XCoord>0</XCoord> 
     <YCoord>0</YCoord> 
     <ZCoord>0</ZCoord> 
    </Location> 
</Locations> 

我希望能夠閱讀它的「豪斯醫生」的一部分,並將其存儲爲一個字符串,任何人可以幫助?

+2

你有什麼試過?我建議['XDocument'](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v = vs.110).aspx)作爲起點。 – 2014-08-27 16:32:45

+1

我建議搜索關於Linq to Xml。 – Mephy 2014-08-27 16:37:31

+1

作爲一個方面說明,通常最好將你的企圖代碼放在其他人的工作中,而不是僅僅要求回答。 – 2014-08-27 16:46:50

回答

1

以下爲使用的XDocument,並抓住所有的根元素位置下方的位置元素,使一個IEnumerable的房子元素全部名。

var xml = "<Locations><Location Name=\"House\"><XCoord>0</XCoord><YCoord>0</YCoord><ZCoord>0</ZCoord></Location></Locations>"; 

var xDoc = XDocument.Parse(xml); 

var attributes = 
     xDoc.Root //Locations 
      .Elements() //Each individual Location 
      .Select(element => element.Attribute("Name").Value); //Grab all the name attribute values 

attributes變量是名稱值的IEnumerable<string>

0

解析XML用的XDocument

XDocument doc = XDocument.Parse(xml); 

選擇

IEnumerable<string> nameValues = 
      from el in doc.Root.Elements() 
      where el.Attribute("Name") != null 
      select el.Attribute("Name").Value; 
+2

您可以使用Linq投影並在Linq Query期間轉換爲字符串。 – 2014-08-27 16:49:29

+0

我根據Cubicle.Jockeys的建議編輯了答案。 – AxdorphCoder 2014-08-27 16:52:22

+0

那麼這不是我的意思,你的代碼將無法工作。我會稍微編輯一下你的答案。 – 2014-08-27 16:54:50