280

I have the following code:

DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

How can I get it to parse XML contained within a String instead of a file?

1
  • 9
    Also note that javax.xml.parsers.DocumentBuilder.parse(string) assumes the string is a uri (terrible...) Commented May 9, 2016 at 13:44

7 Answers 7

524

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

Sign up to request clarification or add additional context in comments.

7 Comments

@shsteimer I am passing in xml string and it is returning null. It does not throw any exception. What must be wrong?
@sattu: You should post it as a new question. It's really hard to tell without seeing your code.
if I have <?XML> it returns an empty node what can i do?
Check that you use the right import statement: import org.xml.sax.InputSource;
Why is everything in Java so gross? Seriously?
|
20

One way is to use the version of parse that takes an InputSource rather than a file

A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader

So something like

parse(new InputSource(new StringReader(myString))) may work. 

Comments

8

Convert the string to an InputStream and pass it to DocumentBuilder

final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);

EDIT
In response to bendin's comment regarding encoding, see shsteimer's answer to this question.

2 Comments

I'd prefer the StringReader because it avoids String.getBytes(), but this should usually work also.
When you call getBytes(), what encoding are you expecting it to use? How are you telling to the XML parser which encoding it's getting? Do you expect it to guess? What happens when you are on a platform where the default encoding isn't UTF-8?
7

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}

Comments

5

javadocs show that the parse method is overloaded.

Create a StringStream or InputSource using your string XML and you should be set.

Comments

0

You can use the Scilca XML Progession package available at GitHub.

XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();

Comments

0

you can try

File f = new File(sac.getFileName());
    if (f.exists()) {
        f.delete();
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();

        // root
        Element root = doc.createElement(Person.KEY_ROOT);
        doc.appendChild(root);

        for(Person p: persons){
            // people element
            Element item = doc.createElement(Person.KEY_ELEMENT);
            root.appendChild(item);

            Element name = doc.createElement(Person.KEY_NAME);
            name.setTextContent(p.getName());
            item.appendChild(name);

            Element gender = doc.createElement(Person.KEY_GENDER);
            gender.setTextContent(p.getGender());
            item.appendChild(gender);

            Element age = doc.createElement(Person.KEY_AGE);
            age.setTextContent(String.valueOf(p.getAge()));
            item.appendChild(age);

            Element occ = doc.createElement(Person.KEY_OCCUPATION);
            occ.setTextContent(p.getOccupation());
            item.appendChild(occ);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");

        // INDENT the xml file is optional, you can
        // uncomment the following statement if you would like the xml files to be more
        // readable
        // transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(f);
        transformer.transform(source, result);

    } catch (Exception e) {
        e.printStackTrace();
    }

use following code to load file

File f = new File(lc.getFileName());
    if (!f.exists()) {
        return;
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        Document doc = db.parse(f);

        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(Person.KEY_ELEMENT);

        for (int i = 0; i < nList.getLength(); i++) {
            Element element = (Element) nList.item(i);
            Person person = new Person();

            if (element.getElementsByTagName(Person.KEY_NAME).item(0) != null)
                person.setName(element.getElementsByTagName(person.KEY_NAME).item(0).getTextContent());

            if (element.getElementsByTagName(Person.KEY_AGE).item(0) != null)
                person.setAge(Integer.parseInt(element.getElementsByTagName(Person.KEY_AGE).item(0).getTextContent()));

            if (element.getElementsByTagName(Person.KEY_OCCUPATION).item(0) != null)
                person.setOccupation(element.getElementsByTagName(Person.KEY_OCCUPATION).item(0).getTextContent());

            if (element.getElementsByTagName(Person.KEY_GENDER).item(0) != null)
                person.setGender(element.getElementsByTagName(Person.KEY_GENDER).item(0).getTextContent());

            persons.add(person);
        }

        this.db.save(lc.getKey(), persons);

    } catch (Exception e) {
        e.printStackTrace();
    }

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.