How to select descendant nodes of XML in c#?

Here is my XML Variable called test having following XML,

<A>
      <X>
        <B  id="ABC">
          <C name="A" />
          <C name="B" />
          <C name="C" />
          <C name="G" />
        </B>
        <B id="ZYZ">
          <C name="A" />
          <C name="B" />
          <C name="C" />
          <C name="D" />
        </B>
      <X>
</A>

I'm creating result XML variable using following c# code,

var result = new XElement(
                    "Result",
                    new[]
                        {                          
                            new XElement("First",test.Descendants("X"))
                        }
                        );

Above code is throwing null exception.

I need the following output XML,

<Result>
  <B  id="ABC">
              <C name="A" />
              <C name="B" />
              <C name="C" />
              <C name="G" />
            </B>
  <B id="ZYZ">
              <C name="A" />
              <C name="B" />
              <C name="C" />
              <C name="D" />
  </B>
</Result>

Any Help appreciated! :)

Answers


You can try this way :

var xml = @"<A>
      <X>
        <B  id=""ABC"">
          <C name=""A"" />
          <C name=""B"" />
          <C name=""C"" />
          <C name=""G"" />
        </B>
        <B id=""ZYZ"">
          <C name=""A"" />
          <C name=""B"" />
          <C name=""C"" />
          <C name=""D"" />
        </B>
      </X>
</A>";
var doc = XDocument.Parse(xml);
var newDoc = new XElement("Result", doc.Root.Element("X").Elements());

//this will print the same output as you expect (the 2nd XML in question)
Console.WriteLine(newDoc.ToString());

Need Your Help

Interactive map in Excel macro

excel excel-vba freeform

I am having troubles with the coding above "9".

Pass An ArrayList<CustomObject> to a function that accepts as parameter an ArrayList<Object> in Java

java android generics arraylist

I am writing a generic java-android function that will accept as one of it's parameters an ArrayList&lt;Object&gt;, so that I can use all over my application regardless of the type of the ArrayList

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.