2011-11-22 90 views
1

我想使用Linq讀取xml文件。該XML文件是由1報頭和N子元素的這樣的:Linq to XML:提高性能

<rootNode> 
     <header> 
      <company name="Dexter Corp." /> 
     </header> 
     <elements> 
      <element>one</element> 
      <element>eleven</element> 
      <element>three</element> 
      <element>four</element> 
      <element>five</element> 
      <element>three</element> 
      <element>two</element> 
      <element>two</element> 
     </elements> 
</rootNode> 

我想檢索這是一個值的元素(例如:2)。只有當我檢索元素時,我才能得到標題元素。

今天,我這樣做:

 string xmlFilePath = @"C:\numbers.xml"; 
     XDocument doc = XDocument.Load(xmlFilePath); 

     var header = doc.Descendants().Elements("header"); 
     var elements = doc.Descendants() 
      .Elements("elements") 
       .Elements("element") 
       .Where(el => el.Value == "two"); 

     // I get this values even if there is no 'elements' 
     string companyName = header.Descendants("company").Attributes("name").Single().Value; 
     string serialNumber = header.Descendants("serial").Single().Value; 


     return elements.Select(el => new {Company = companyName, Serial = serialNumber, Value = el.Value}); 

是否有更好的方法來解析該文件? (並提高性能?)

回答

5

如果性能對您很重要,則不應使用doc.Descendants()在某個已知位置查找元素。它總是掃描整個文檔,如果文檔很大,文檔很慢。

相反,這樣做

doc.Root.Element("header") 

doc.Root.Element("elements") 
     .Elements("element") 
     .Where(el => el.Value == "two") 

這應該是要快得多。