2010-12-05 11 views
2

XML에서 속성과 중첩 된 요소를 사용하는 것이 어렵습니다. Type="Mobile" 특성을 가진 Phone 요소 만 추출하고 주소를 한 줄로 인쇄하려면 LINQ에서 어떻게해야합니까?LINQ에서이 XML을 쿼리하는 방법은 무엇입니까?

난 그냥이 같은 출력을 생성하려면 : 아래에있는 내 샘플 XML 파일은,

332-899-5678 | 123 Main, St Mercer Island, WA 68042 

도와주세요

<Contacts> 
    <Contact> 
    <Name>Patrick Hines</Name> 
    <Phone Type="Home">206-555-0144</Phone> 
    <Phone Type="Work">425-555-0145</Phone> 
    <Phone Type="Mobile">332-899-5678</Phone> 
    <Address> 
     <Street1>123 Main St</Street1> 
     <City>Mercer Island</City> 
     <State>WA</State> 
     <Postal>68042</Postal> 
    </Address> 
    </Contact> 
</Contacts> 

답변

3
string xml = @"<Contacts> 
    <Contact> 
    <Name>Patrick Hines</Name> 
    <Phone Type=""Home"">206-555-0144</Phone> 
    <Phone Type=""Work"">425-555-0145</Phone> 
    <Phone Type=""Mobile"">332-899-5678</Phone> 
    <Address> 
     <Street1>123 Main St</Street1> 
     <City>Mercer Island</City> 
     <State>WA</State> 
     <Postal>68042</Postal> 
    </Address> 
    </Contact> 
    <Contact> 
    <Name>Dorothy Lee</Name> 
    <Phone Type=""Home"">910-555-1212</Phone> 
    <Phone Type=""Work"">336-555-0123</Phone> 
    <Phone Type=""Mobile"">336-555-0005</Phone> 
    <Address> 
     <Street1>16 Friar Duck Ln</Street1> 
     <City>Greensboro</City> 
     <State>NC</State> 
     <Postal>27410</Postal> 
    </Address> 
    </Contact> 
</Contacts>"; 

XDocument document = XDocument.Parse(xml); 
var query = from contact in document.Descendants("Contact") 
      let address = contact.Element("Address") 
      select new 
      { 
       Name = contact.Element("Name").Value, 
       MobilePhone = contact.Elements("Phone").Where(ele => ele.Attribute("Type").Value == "Mobile").First().Value, 
       Street1 = address.Element("Street1").Value, 
       City = address.Element("City").Value, 
       State = address.Element("State").Value, 
       Postal = address.Element("Postal").Value 
      }; 

foreach (var item in query) 
{ 
    Console.WriteLine("{0} | {1}, {2}, {3} {4}", item.MobilePhone, item.Street1, item.City, item.State, item.Postal); 
} 
+0

고마워 다시 선생님 :) – yonan2236

2

아마도 뭔가 같은 :

var rows = 
    from contact in root.Elements("Contact") 
    let phone = (string)contact.Elements("Phone").FirstOrDefault(
      (string)p => p.Attribute("Type") == "Mobile") 
    let addr = contact.Element("Address") 
    select phone + " | " + 
     (string)addr.Element("Street1") + " | " + 
     (string)addr.Element("City") + " | " + 
     ... 
관련 문제