I have a string in XML format. I need to convert that to an XML file. How would I do this?
-
1You definitely need to provide more information. Programming language or environment would be a good start.Andy West– Andy West2009-12-17 05:07:14 +00:00Commented Dec 17, 2009 at 5:07
-
its java,i just need to convert hte string that is having xml data to an xml filesarah– sarah2009-12-17 05:25:19 +00:00Commented Dec 17, 2009 at 5:25
Add a comment
|
4 Answers
Java:
XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")));
If you use C#, try this
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument XDoc = new XmlDocument();
XDoc.LoadXml("<Root><body>hello</body></Root>");
XDoc.Save(@"D:\Temp\MyXMl.xml");
}
Comments
It's a string which contains XML? Then just write it to a file. In Java? A FileWriter should work just fine.
2 Comments
jarnbjo
It's not that easy. The character encoding must be determined from the document header if present, otherwise UTF-8 must be chosen. Simply using a FileWriter and the platform's default encoding is in most situations wrong.
Paul Clapham
That's true, I was assuming that it wouldn't have a prolog. If it doesn't, then you would have to use a writer using UTF-8 or UTF-16 as its encoding.
Use XStream library it is quite simple: http://x-stream.github.io/tutorial.html
// object -> XML -> File
XStream xstream = new XStream(driver);
String data = xstream.toXML(metaData);
// XML -> object
XStream xstream = new XStream(new JettisonMappedXmlDriver());
YourClass obj = (UourClass)xstream.fromXML(jSON);
Comments
Just write the string to a file with .xml extension.Here is the code:
import java.io.*;
class writeXML {
public static void main(String args[])
{
try{
String s="<xmltag atr=value>tag data</xmltag>";
FileWriter fr= new FileWriter(new File("a.txt"));
Writer br= new BufferedWriter(fr);
br.write(s);
br.close();
}
catch(Exception e)
{
}
}
}