1

I have following XML string:

<persons>
    <person>
        <name>Someone</name>
        <age>27</age>
    </person>
    <person>
        <name>Otherone</name>
        <age>43</age>
    </person>
</persons>

I want to take this string and to get from it a DOM object. It could be any XML string (not from file!).

Sorry for this newbie question,Thanks a lot for helpers.

2 Answers 2

3
org.w3c.dom.Document doc =
  javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(
        ).parse(
   new org.xml.sax.InputSource(new java.io.StringReader(xmlString)));
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks,It returns an exception if the xml string is not well formated,How I can work with non-well formated xml strings?
@Yosi You can catch the exception and report the error. If you want to fetch data from a string which may or may not contain well-formed XML you might want use regular expressions.
@Yosi another approach: use SAX parser and handle tags/attrs/characters until the parser hasn't met the error. Maybe you can explain what you want to do?
Hi,I am sorry ,it works very well with unformated xml string .
0

Try this:

import java.io.IOException;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;



public class String2XML {

    public static void main(String[] args) throws SAXException, IOException {
        String xml="<persons><person><name>Someone</name><age>27</age></person><person><name>Otherone</name><age>43</age></person></persons>";
        DOMParser parser = new DOMParser();
        parser.parse(new InputSource(new java.io.StringReader(xml))); 
        Document doc = parser.getDocument();
        System.out.println("String2XML.main()-"+doc.toString());
    }
}

Dont forget including xercesImpl.jar and xml-apis.jar in your classpath. You can find them here http://archive.apache.org/dist/xml/xerces-j/binaries/

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.