2014-08-27 99 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