DJ메탈짱™의 Free Style

[C#] LINQ, XML파싱, xml to LINQ, foreach,같은Depth 동일 Element반환 본문

일(job)/MS(Microsoft)

[C#] LINQ, XML파싱, xml to LINQ, foreach,같은Depth 동일 Element반환

뽀&쏭 2015. 12. 31. 13:14

 

동일한 Depth의 Element의 값들을 반환하는 경우 아래 (예제2) 코드 참고.

(예제1)처럼 Descendants을 통해서 반복문의 경우에는 동일한 Element의 값을 반환하지는 않는다. 

 

        <cabinColumnDetails>
          <!-- 대상 열 -->
          <seatColumn>A</seatColumn>
          <!-- 대상 열의 특성 (여러 속성을 가질 수 있음) -->
          <columnCharacteristic>W</columnCharacteristic>
          <columnCharacteristic>A</columnCharacteristic>
        </cabinColumnDetails>
        <cabinColumnDetails>
          <seatColumn>B</seatColumn>
          <columnCharacteristic>A</columnCharacteristic>
        </cabinColumnDetails>
        <cabinColumnDetails>
          <seatColumn>C</seatColumn>
          <columnCharacteristic>A</columnCharacteristic>
        </cabinColumnDetails>
        <cabinColumnDetails>
          <seatColumn>D</seatColumn>
          <columnCharacteristic>W</columnCharacteristic>
          <columnCharacteristic>A</columnCharacteristic>
        </cabinColumnDetails>
 

 

(예제1)

StringBuilder sb = new StringBuilder();

var rltLinq = from config1 in xmlDoc.Descendants("cabinColumnDetails")

             select new

             {

cabinColumnDetails = (string)config1.Element("columnCharacteristic").Value

};

foreach (var rlt in rltLinq)

{

sb.AppendLine("cabinColumnDetails:"+rlt.cabinColumnDetails);

}

MessageBox.Show(sb.ToString());

(예제2)

StringBuilder sb = new StringBuilder();

foreach (XElement r in xmlDoc.Descendants("cabinColumnDetails"))

{

foreach (XElementitem in r.Elements("columnCharacteristic"))

        {

                sb.AppendLine(item.Value);

}

}

MessageBox.Show(sb.ToString());