Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XML to string using C#

Tags:

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?

like image 656
shakz Avatar asked May 28 '11 10:05

shakz


People also ask

How to convert XML object to string?

You will need to serialize your xmlDoc back to XML once you have made the changes: var s = new XMLSerializer(); var newXmlStr = s. serializeToString(xmlDoc); Now you can do what you need to do with the string of updated XML, overwrite your xml variable, or send it to the server, or whatever...

Can we convert XML to string?

Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.


1 Answers

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 
like image 131
Kimtho6 Avatar answered Oct 16 '22 20:10

Kimtho6