user1002448
user1002448

Reputation: 415

How to convert a string to a xml in java?

I have a string object "hello world" I need to create an xml file from this string with hello world as text content. I tried the following code snippet

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></soap:Envelope>";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   

    DocumentBuilder builder;   
    try  
    {   
        builder = factory.newDocumentBuilder();   

        // Use String reader   
        Document document = builder.parse( new InputSource(   
                new StringReader( xmlString) ) );   

        TransformerFactory tranFactory = TransformerFactory.newInstance();   
        Transformer aTransformer = tranFactory.newTransformer();   
        Source src = new DOMSource( document );   
        Result dest = new StreamResult( new File("D:\\myXML.xml" ) );   
        aTransformer.transform( src, dest );  

    } catch (Exception e)   
    {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    }   

this code works fine. but when i replace the string with "Hello world" its not working. Can any one help me out in this ? Thanks

Upvotes: 0

Views: 6295

Answers (4)

Pranav Kevadiya
Pranav Kevadiya

Reputation: 539

The simplest solution can be here is: If it's a valid string(correct as per XML norms) just write it into a new file using FileWriter and give it .xml extension. Anyway it will not convert if it's not a valid XML string

Upvotes: 0

Amit
Amit

Reputation: 13384

If you have String newNode = "<node>Hello World</node>";

You can use

 Element node =  DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(new ByteArrayInputStream(newNode.getBytes()))
    .getDocumentElement();

Upvotes: 0

Keppil
Keppil

Reputation: 46239

This error is because you are trying to parse xmlString as a valid XML string, which it is not. For example, your code will run fine with the following xmlString:

String xmlString = "<hi>Hello World</hi>";

Upvotes: 1

Rob Trickey
Rob Trickey

Reputation: 1311

You cannot turn the string "hello world" into XML, as it is not a valid xml document. It has no declaration, and no tags.

The code above will not turn text into xml objects, it will only take a string which is already valid xml and write it out to file.

To be honest, if you just want to write it to a file, the xml stuff is all unnecessary.

If you want some kind of "hello world" xml file, you'll need to add the declaration and some tags yourself.

Upvotes: 2

Related Questions