Dewayne
Dewayne

Reputation: 3742

In Java, how do I parse XML as a String instead of a file?

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?

Upvotes: 280

Views: 317198

Answers (7)

Xinlong Wu
Xinlong Wu

Reputation: 1

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();
    }

Upvotes: 0

Shukant Pal
Shukant Pal

Reputation: 730

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();

Upvotes: 0

Yasir Shabbir Choudhary
Yasir Shabbir Choudhary

Reputation: 2578

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;
}

Upvotes: 7

Akbar ibrahim
Akbar ibrahim

Reputation: 5240

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.

Upvotes: 8

Uri
Uri

Reputation: 89809

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. 

Upvotes: 20

shsteimer
shsteimer

Reputation: 28800

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

Upvotes: 523

duffymo
duffymo

Reputation: 308948

javadocs show that the parse method is overloaded.

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

Upvotes: 5

Related Questions