DotNetDeveloper
DotNetDeveloper

Reputation: 587

Read Child nodes including text and node using XPath from XElement ? LinQ

Using old way of doing via XmlDocument,

string xmlstring = "<root><profile><Name>John</Name><Age>23</Age></profile></root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);
string childNodes = xmlDoc.SelectSingleNode("root/Profile").InnerXml;

// output of childNodes would be => "<Name>John</Name><Age>23</Age>";

what is the equivalent of doing the above execution in LinQ when you have XElement variable. I see XPathSelectElement method in XElement but it doesn't return the child nodes + Child nodes text. Any Ideas?

Upvotes: 1

Views: 693

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500845

I wouldn't use XPath at all for this. I'd use:

XDocument doc = XDocument.Parse(xmlString);
var nodes = doc.Root
               .Elements("profile")
               .DescendantsAndSelf();

That give the profile nodes and all their descendants. It's not really clear what you're trying to do with the results, but if you can give more details I should be able to come up with the appropriate code.

Upvotes: 3

Related Questions