2016-11-29 50 views
4

我有这样的XML代码:性能方法从XML获得单个元素 - C#

<Body> 
    <Schoolyear>2016</Schoolyear> 
    <ClassLeader> 
    <Id>200555</Id> 
    <Name>Martin</Name> 
    <Short>ma</Short> 
    </ClassLeader> 
    <Info> 
    some very useful information :) 
    </Info> 
</Body> 

我只需要一个标签,E。 G。学年

我尝试这样做:

foreach (XElement element in Document.Descendants("Schoolyear")) 
{ 
    myDestinationVariable = element.Value; 
} 

它的工作原理,但我想,也许有一个更好的性能和更容易的解决方案。

+5

你有没有打过电话'FirstOrDefault( )'而不是?这里不需要循环... –

+2

xml.DocumentElement.SelectSingleNode(“/ body/Schoolyear”)。InnerText – Fuzzybear

+1

我相信FirstOrDefault()反过来在其内部使用foreach。因此,考虑到性能,最好选择SelectSingleNode。 –

回答

2

你可以把它用LINQ或只使用Element与指定的XName

添加命名空间

using System.Xml.Linq; 

,并使用其中一个例子

 string xml = @"<Body> 
    <Schoolyear>2016</Schoolyear> 
    <ClassLeader> 
    <Id>200555</Id> 
    <Name>Martin</Name> 
    <Short>ma</Short> 
    </ClassLeader> 
    <Info> 
    some very useful information :) 
    </Info> 
</Body>"; 

XDocument dox = XDocument.Parse(xml); 

var exampl1 = dox.Element("Body").Element("Schoolyear").Value; 

var exampl2 = dox.Descendants().FirstOrDefault(d => d.Name == "Schoolyear").Value; 
+0

谢谢你的工作,但ist更快然后我的代码? –