Is it possible to convert a string to XML? I have an XML document coming in to my web page through Request.QueryString["xml"] in string format. I need to create a new XML file made up of the XML in this string. Can anybody help me out?
Instantiate a XmlDocument object, then call the LoadXml() method with your string. If it loads successfully (i.e. if it was valid XML), you can then call .Save() method to write it to a file.
Note that the XmlDocument class is only good for XML up to about a megabyte's worth.
Chip H.
If you want to get the best response to a question, please check out FAQ222-2244 first
If your string doesn't contain the namespaces then you can use the following piece of code:
string xmlFrag ="<book> " +
"<title>Pride And Prejudice</title>" +
"<genre>novel</genre>" +
"</book>";
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlFrag);
doc.Save("myfile.xml"
}
catch (Exception ex)
{
string sMsg = ex.GetType() + ex.Message;
throw new Exception (ex);
}
If your string contains namespaces then use XmlTextReader:
XmlParserContext context = new XmlParserContext(...);
XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.