Converting xml to string using C#

后端 未结 3 1841
你的背包
你的背包 2020-12-08 08:08

I have a function as below

public string GetXMLAsString(XmlDocument myxml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(myxml);

           


        
相关标签:
3条回答
  •    public string GetXMLAsString(XmlDocument myxml)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                {
                   myxml.WriteTo(xmlTextWriter);
                   return stringWriter.ToString();
                }
    
            }    
    }
    
    0 讨论(0)
  • 2020-12-08 08:51

    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
    
    0 讨论(0)
  • 2020-12-08 08:52

    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;
    }
    
    0 讨论(0)
提交回复
热议问题