Search code examples
c#xml

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?


Solution

  • 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