1

How can I write a program that turns this XML string

<outer>
  <inner>
    <boom>
      <name>John</name>
      <address>New York City</address>
    </boom>

    <boom>
      <name>Daniel</name>
      <address>Los Angeles</address>
    </boom>

    <boom>
      <name>Joe</name>
      <address>Chicago</address>
    </boom>
  </inner>
</outer>

into this string

name: John
address: New York City

name: Daniel
address: Los Angeles

name: Joe
address: Chicago

Can LINQ make it easier?

roger.james
  • 1,478
  • 1
  • 11
  • 23

1 Answers1

8

With Linq-to-XML:

XDocument document = XDocument.Load("MyDocument.xml");  // Loads the XML document with to use with Linq-to-XML

var booms = from boomElement in document.Descendants("boom")  // Go through the collection of boom elements
            select String.Format("name: {0}" + Environment.NewLine + "address: {1}",  // Format the boom item
                                 boomElement.Element("name").Value,  // Gets the name value of the boom element
                                 boomElement.Element("address").Value);  // Gets the address value of the boom element

var result = String.Join(Environment.NewLine + Environment.NewLine, booms);  // Concatenates all boom items into one string with

Update

To generalize it with any elements in boom, the idea is the same.

var booms = from boomElement in document.Descendants("boom")  // Go through the collection of boom elements
            let boolChildren = (from boomElementChild in boomElement.Elements()  // Go through the collection of elements in the boom element
                                select String.Format("{0}: {1}",  // Formats the name of the element and its value
                                                     boomElementChild.Name.LocalName,  // Name of the element
                                                     boomElementChild.Value))  // Value of the element
            select String.Join(Environment.NewLine, boolChildren);  // Concatenate the formated child elements

The first and last lines remains the same.

Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
  • Can you generalize this to "loop" through the elements within "boom" (not assuming the fixed "name" and "address")? – roger.james Jul 23 '13 at 13:05
  • Thanks, that works. Can you add another update that allows me to filter out boom elements satisfying some arbitrary condition, e.g. where `address` contains "New" (in this case only "New York City", and only the first boom would show up)? – roger.james Jul 23 '13 at 15:22
  • I created a separate question for this, feel free to take a shot at it: http://stackoverflow.com/questions/17815090/adding-a-condition-filter-to-this-linq-code – roger.james Jul 23 '13 at 15:53