2016-11-29 52 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更快然後我的代碼? –