Reputation: 359
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! :)
Upvotes: 0
Views: 2636
Reputation: 89335
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());
Upvotes: 2
Reputation: 2123
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
To get all nodes use XPath expression /Names/Name. The first slash means that the node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the nodes.
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
Upvotes: 1