0

I have a string in XML format. I need to convert that to an XML file. How would I do this?

2
  • 1
    You definitely need to provide more information. Programming language or environment would be a good start. Commented Dec 17, 2009 at 5:07
  • its java,i just need to convert hte string that is having xml data to an xml file Commented Dec 17, 2009 at 5:25

4 Answers 4

10

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");
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's a string which contains XML? Then just write it to a file. In Java? A FileWriter should work just fine.

2 Comments

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.
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.
1

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

0

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)
        {
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.