Get full XElement string with mixed content

Say I have the following content in an XElement object

 <root>Hello<child>Wold</child></root> 

If I use XElement.ToString() , this gives me

 "<root xmnls="someschemauri">Hello<child>World</child></root>" 

If I use XElement.Value, I will get

 "Hello World" 

I need to get

 "Hello <child>World</child>" 

What is the correct function for this (if any)?

+7
source share
6 answers

Solution for .NET 4

 var result = String.Join("", rootElement.Nodes()).Trim(); 

Full code (for .NET 3.5):

 XElement rootElement = XElement.Parse("<root>Hello<child>Wold</child></root>"); var nodes = rootElement.Nodes().Select(n => n.ToString()).ToArray(); string result = String.Join("", nodes).Trim(); Console.WriteLine(result); // writes "Hello<child>World</child>" 

Quick solution without combining all nodes:

 XElement rootElement = XElement.Parse("<root>Hello<child>Wold</child></root>"); var reader = rootElement.CreateReader(); reader.MoveToContent(); string result = reader.ReadInnerXml(); 
+4
source

This worked pretty nicely:

 //SOLUTION BY Nenad var element = XElement.Parse("<root>Hello<child>World</child></root>"); string xml = string.Join("", element.DescendantNodes().Select(e => e.ToString())); Debug.WriteLine(xml); 

Final conclusion: Hello<child>Wold</child>World


Try # 3

 XDocument xDoc = XDocument.Parse(@"<root>Hello<child>World</child></root>"); XElement rootElement = xDoc.Root; Debug.WriteLine(rootElement.Value + rootElement.FirstNode.ToString()); 
+1
source

This will do:

 var element = XElement.Parse("<root>Hello<child>Wold</child></root>"); string xml = string.Join("", element.Nodes().Select(e => e.ToString())); 

For .NET 3.5 (if agreed):

 var element = XElement.Parse("<root>Hello<child>Wold</child></root>"); string xml = string.Join("", element.Nodes().Select(e => e.ToString()).ToArray()); 
+1
source

I don’t have time to check this out, but try:

 var inners = from n in xelementVariableName.Nodes() select n; return String.Join(String,Empty, inners); 

Tested:

 public static string ReturnInnerXml() { var doc = XDocument.Parse(@"<root>Hello<child>World</child></root>"); var root = doc.Root; if (root == null) { throw new InvalidOperationException("No root"); } var inners = from n in root.Nodes() select n; return String.Join(String.Empty, inners); } 

This gives:

 Hello<child>World</child> 

Using .NET 4.0

0
source

Here he is:

 var element = XElement.Parse("<root>Hello<child>Wold</child></root>"); string xml = string.Join("", element.Nodes().Select(e => e.ToString()).ToArray()); 

Returns Hello<child>Wold</child> and works on .NET 3.5

0
source

Extension method based on the fastest solution:

 public static class XElementExtension { public static string InnerXML(this XElement el) { var reader = el.CreateReader(); reader.MoveToContent(); return reader.ReadInnerXml(); } } 

Then just name it: xml.InnerXML();

0
source

All Articles