HOW DO I SELECT ROWS INTO COLUMNS?

Ida B Wells

Total Post:30

Points:210
Posted by  Ida B Wells
C# 
C#
 1379  View(s)
Ratings:
Rate this:

Xml is as follows.

<System>
  <ID></ID>
  <Name></Name>
  <Monitor>
    <ID></ID>
    <Type></Type>
    <Alert>
      <ID></ID>
      <Status></Status>
    </Alert>
    <Alert>
      <ID></ID>
      <Status></Status>
    </Alert>
  </Monitor>
</System>
<System>
  <ID></ID>
  <Name></Name>
  <Monitor>
    <ID></ID>
    <Type></Type>
    <Alert>
      <ID></ID>
      <Status></Status>
    </Alert>
  </Monitor>
</System>

I want to traverse it like this

XElement xmlDoc = XElement.Load(@"xml");
var q = from el in xmlDoc.Elements("System") select el;
 
foreach(el in q) {
    Console.WriteLine(el.ID);
    Console.WriteLine(el.Name);
 
    if (el.Monitor) {
        foreach (mon in el.Monitor) {
            Console.WriteLine(el.ID);
            Console.WriteLine(el.Type);
 
            if (mon.Alert) {
                foreach (alert in mon.Alert) {
                    Console.WriteLine(alert.ID);
                    Console.WriteLine(alert.Status);
                }
            }
        }
    }
}

Currently I loop through each several times and use if to check field and then assign value to a variable. Then I have to loop through it again. Is there an easier way, and should I use plain LINQ or LINQ-TO-XML?

  1. ben reitman

    Post:96

    Points:676
    Re: How do I select rows into columns?

    Hey Ida!

    If you want to traverse it like that you can:

    var xml = @"
    <Root>
    <System>
    <ID>1</ID>
    <Name>One</Name>
    <Monitor>
        <ID>2</ID>
        <Type>Two</Type>
        <Alert>
        <ID>3</ID>
        <Status>Three</Status>
        </Alert>
        <Alert>
        <ID>4</ID>
        <Status>Four</Status>
        </Alert>
    </Monitor>
    </System>
    <System>
    <ID>5</ID>
    <Name>Five</Name>
    <Monitor>
        <ID>6</ID>
        <Type>Six</Type>
        <Alert>
        <ID>7</ID>
        <Status>Seven</Status>
        </Alert>
    </Monitor>
    </System>
    </Root>
    ";
    XElement xmlDoc = XElement.Parse(xml);
    var q = xmlDoc.Elements("System");
    foreach(var el in q) {
        Console.WriteLine(el.Element("ID").Value);
        Console.WriteLine(el.Element("Name").Value);
        foreach(var mon in el.Elements("Monitor")) {
            Console.WriteLine(mon.Element("ID").Value);
            Console.WriteLine(mon.Element("Type").Value);
            foreach(var alert in el.Elements("Alert")) {
                Console.WriteLine(alert.Element("ID").Value);
                Console.WriteLine(alert.Element("Status").Value);
            }
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!