2010-04-26 71 views
2

我有一個XML文檔,像這樣:的LINQ to XML文檔遍歷

<?xml version="1.0" encoding="utf-8" ?> 
<demographics> 
    <country id="1" value="USA"> 
     <state id ="1" value="California"> 
      <city>Long Beach</city> 
      <city>Los Angeles</city> 
      <city>San Diego</city> 
     </state> 
     <state id ="2" value="Arizona"> 
      <city>Tucson</city> 
      <city>Phoenix</city> 
      <city>Tempe</city> 
     </state> 
    </country> 
    <country id="2" value="Mexico"> 
     <state id ="1" value="Baja California"> 
      <city>Tijuana</city> 
      <city>Rosarito</city>    
     </state> 
    </country> 
</demographics> 

如何做做這樣的事情我設置LINQ查詢: 1.獲取所有國家 2.獲取所有國家在國家 3.將所有城市都置於特定國家的狀態?

我給它一個嘗試,我有點糊塗何時使用Elements [「NodeName」]和後裔等。我知道我不是最聰明的XML人。 XML文件的格式是否適用於簡單遍歷?

回答

4

從文件加載文檔

IEnumerable<string> countries = document 
    .Descendants("country") 
    .Select(element => element.Attribute("value").Value); 

爲了讓所有的規定,在美國境內:

IEnumerable<string> states = document 
    .Descendants("country") 
    .Where(element => element.Attribute("value").Value == "USA") 
    .Elements("state") 
    .Select(element => element.Attribute("value").Value); 

爲了讓所有的城市美國/加利福尼亞里面:

IEnumerable<string> cities = document 
    .Descendants("country") 
    .Where(element => element.Attribute("value").Value == "USA") 
    .Elements("state") 
    .Where(element => element.Attribute("value").Value == "California") 
    .Elements("city") 
    .Select(element => element.Value); 

你也可能想看看XPath查詢(你需要using System.XML.XPath):

IEnumerable<string> cities = document 
    .XPathSelectElements("/demographics/country[@value='USA']/state[@value='California']/city") 
    .Select(element => element.Value); 
1

像這樣:

XDocument document = XDocument.Load("input.xml"); 

要得到所有國家的名字:

var countries = document.Root.Elements("country"); 
var states = country.Elements("state"); 
var cities = state.Elements("city"); 
1
var doc = XDocument.Load("myxml.xml"); 


var countries = doc.Descendants("country") 
        .Attributes("value") 
        .Select(a => a.Value); 

var states = doc.Descendants("country") 
        .Single(country => country.Attribute("value").Value == "USA") 
        .Elements("state") 
        .Attributes("value") 
        .Select(a => a.Value); 

var cities = doc.Descendants("state") 
        .Single(state => state.Attribute("value").Value == "California") 
        .Elements("city") 
        .Select(e => e.Value); 

結果將具有countries,statescities,類型爲IEnumerable<string>

另外值得注意的是,執行(即解析)將被延遲,直到您實際枚舉這些IEnumerable<string>變量中的值。這有時會導致意想不到的性能問題。例如,如果您打算顯示所有數據,並將其綁定到某個UI控件,則用戶界面可能會變得遲鈍,因爲它意識到它確實需要解析它。 (它甚至可能會阻塞UI線程,而不是您的工作線程?不確定。)要解決此問題,請在末尾添加.ToList(),以獲得非延期的List<string> s。