Read nodes in XDocument
-
Monday, May 21, 2012 10:03 PM
Hello. I've read a lot of tech docs but have been unsuccessful resolving my issue.
I am returned a string which I convert to XML, as follows:
<?xml version="1.0" encoding="UTF-8"?>
<MyType xmlns="http://myurl.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<myHeader>
<HeaderElement1>
<DateTime>2012-05-21T14:54:57-06:00</DateTime>
</HeaderElement1>
<HeaderElement2>
<Value1>123</Value1>
</HeaderElement2>
</myHeader>
<Response>
<Status>
<Node1>Hello</Node1>
<Node2>World</Node2>
<AdditionalDetail>
<Name>John Doe</Name>
</AdditionalDetail>
</Status>
</Response>
</myType>So far, I have been able to print out all the node names doing something like:
XDocument doc= XDocument.Parse(responsestring);
foreach( XElement xe in doc.Descendants())
Console.WriteLine(xe.Name.ToString());I get an answer like:
{http://myurl.com}MyType
{http://myurl.com}myHeader
...
{http://myurl.com}ResponseSo, I wanted to get all the node names and values under the Response section.
I tried this:
XDocument doc= XDocument.Parse(responsestring);
foreach ( XElement xe in doc.Descendants("{http://myurl.com}Response"))
Console.WriteLine(xe.Name.ToString())All I get back is '{http://myurl.com}Response'.
If I change it to Console.WriteLine(xe.Value.ToString()), I get all the values in one string like:
HelloWorldJohn Doe
I won't always get the same nodes so I'd like to get the node names and values individually.
Thank you very much!!
All Replies
-
Tuesday, May 22, 2012 2:42 AMModerator
Hello, I don't know exactly what you want to achieve. If you want to parse all children of the Response element, you need to define a recursive method:
private static void ParseChildElements(XElement parent)
{
foreach (XElement element in parent.Elements())
{
Console.Write(element.Name.LocalName + "\r\n");
if (element.HasElements)
{
// Do not print value. Instead, parse child elements.
ParseChildElements(element);
}
else
{
Console.Write(element.Value + "\r\n");
}
}
}Then invoke it:
XNamespace xNamespace = "http://myurl.com";
XElement responseElement = doc.Descendants(xNamespace + "Response").First();
ParseChildElements(responseElement);Also note your question has nothing to do with WCF. If you have further questions, please post them on the LINQ forum: http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/threads
Lante, shanaolanxing This posting is provided "AS IS" with no warranties, and confers no rights.
If you have feedback about forum business, please contact msdnmg@microsoft.com. But please do not ask technical questions in the email.- Marked As Answer by Hiline1961 Tuesday, May 22, 2012 5:00 PM
-
Tuesday, May 22, 2012 5:00 PM
Thank you very much, Yi-Lun.
And, sorry for posting in the wrong forum.
Thanks again!!

