Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve full string of XElement with mixed content

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)?

like image 311
Machinegon Avatar asked Mar 07 '13 19:03

Machinegon


4 Answers

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(); 
like image 114
Sergey Berezovskiy Avatar answered Nov 08 '22 08:11

Sergey Berezovskiy


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());
like image 33
Magnum Avatar answered Nov 08 '22 10:11

Magnum


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());
like image 1
Nenad Avatar answered Nov 08 '22 09:11

Nenad


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();

like image 1
Mike Keskinov Avatar answered Nov 08 '22 09:11

Mike Keskinov