Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XElement to string

People also ask

How to convert XElement to String using c#?

Show activity on this post. XElement xml = new XElement("XML", new XElement ("TOKEN",Session["Token"]), new XElement("ALL_INCLUSIVE", "0"), new XElement("BEACH", "0"), new XElement("DEST_DEP", ddlDest. SelectedValue. ToString()), new XElement("FLEX", "0") );

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


ToString should most definately work. I use it all the time. What does it return for you in this case? An empty string? My guess is that something went wrong building your XElement. To debug, rewrite the code to add each of the child XElements separately, so that you can step through your code and check on each of them. Then before you execute the .ToString, in the Locals window, look at the [xml] variable expanded to xml.

In short, your problem is happening before you ever get to the ToString() method.


ToString works, but it returns content including XElement tag itself. If you need for Inner XML without root tag ("" in your example), you may use the following extension method:

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