shakz
shakz

Reputation: 639

Converting XML to string using C#

I have a function as below

public string GetXMLAsString(XmlDocument myxml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(myxml);
       
        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        doc.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

I'm passing an XML to this method from an another method. But in the doc.loadxml(), the system is expecting a string and since I'm passing an XML, it throws error.

How to solve this issue?

Upvotes: 26

Views: 176100

Answers (4)

Ivette
Ivette

Reputation: 1

String pathFile = "C:\File.XML"; String readConfiguration = File.ReadAllText(pathFile , Encoding.Unicode);

Upvotes: -1

Kimtho6
Kimtho6

Reputation: 6184

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

Upvotes: 61

Chris Moutray
Chris Moutray

Reputation: 18399

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Upvotes: 32

danyolgiax
danyolgiax

Reputation: 13116

   public string GetXMLAsString(XmlDocument myxml)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
               myxml.WriteTo(xmlTextWriter);
               return stringWriter.ToString();
            }

        }    
}

Upvotes: 4

Related Questions