Let's 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 proper function to do this(if there is one)?
Solution for .NET 4
var result = String.Join("", rootElement.Nodes()).Trim();
Complete 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>"
Fast solution without joining all nodes:
XElement rootElement = XElement.Parse("<root>Hello<child>Wold</child></root>");
var reader = rootElement.CreateReader();
reader.MoveToContent();
string result = reader.ReadInnerXml();
This worked rather 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 output: 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());
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 that was the point of question):
var element = XElement.Parse("<root>Hello<child>Wold</child></root>");
string xml = string.Join("", element.Nodes().Select(e => e.ToString()).ToArray());
Extension method based on fastest know solution:
public static class XElementExtension
{
public static string InnerXML(this XElement el) {
var reader = el.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
}
Then simple call it: xml.InnerXML();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With