2010-04-26 4 views
2

는이 같은 XML 문서가 :Linq는 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> 

을 어떻게 같이 일을위한 I 설정 LINQ 쿼리 : 가져 1. 모든 국가 2. 나라 에 모든 주를 가져옵니다 3. 모든 도시를 국가의 안쪽에 가져 가야합니까?

나는 그것을 시험해 보았고 요소 [ "NodeName"]과 자손을 사용할 때 혼란 스럽다. 나는 주변에서 가장 밝은 XML 녀석이 아니라는 것을 안다. XML 파일의 형식이 간단한 순회 (traversal)에도 맞습니까? 이처럼

답변

4

파일에서 문서를로드

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

는 모든 상태를 얻으려면 그 국가 '미국'내에 있음 :

0 미국/캘리포니아 안에 모든 도시를 효율적으로 활용하려면 다음

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); 

결과 것이다 :

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); 

당신은 또한 (당신이 using System.XML.XPath 필요) XPath 쿼리를보고 할 수 있습니다 countries, statescitiesIEnumerable<string>입니다.

변수 (IEnumerable<string>)의 값을 실제로 열거 할 때까지 실행 (즉 구문 분석)이 지연된다는 점에 유의해야합니다. 이로 인해 의도하지 않은 성능 문제가 발생할 수 있습니다. 예를 들어 어쨌든 모든 데이터를 표시하려는 경우 데이터를 일부 UI 컨트롤에 바인딩하면 결국 구문 분석이 필요하다는 것을 알게되므로 사용자 인터페이스가 느려질 수 있습니다. (작업자 스레드 대신 UI 스레드를 차단할 수도 있습니다. 확실하지 않습니다.)이 문제를 해결하려면 대신 List<string>을 지연시키기 위해 .ToList()을 끝에 추가하십시오.