Ziya Guven Koylu
Ziya Guven Koylu

Reputation: 1

Parse with digester

My xml is like <value>value1</value> i want to parse it using commons-digester and want to get "value1" as a String object

Upvotes: 0

Views: 1751

Answers (2)

Navin Peiris
Navin Peiris

Reputation: 2596

Going with Lukasz answer, if you don't want to create another object to hold the value, then you can just push a StringBuilder onto the stack and then call append using addCallMethod. I've reproduced the code here for clarity:

public class StringExtractor {
    public static void main(String[] args) throws IOException, SAXException {
        final String xml = "<value>value1</value>";

        final Digester digester = new Digester();
        digester.push(new StringBuilder());
        digester.addCallMethod("*/value", "append", 1);
        digester.addCallParam("*/value", 0);

        final String value = digester.parse(new StringReader(xml)).toString();
        System.out.println(value);
    }
}

Upvotes: 1

Lukasz
Lukasz

Reputation: 7662

I don't think it is possible to load "value1" directly into String instance (by addObjectCreate), because String is immutable. Instead of this, I'd force digester to call a method. Short sample:

import java.io.File;
import org.apache.commons.digester.Digester;

public class Tester {
    public static void main(String[] args) throws Exception {
        Tester t = new Tester();
        t.go();
    }

    private String read;

    void go() throws Exception {
        Digester digester = new Digester();
        digester.push(this);
        digester.addCallMethod("value", "readString", 1);
        digester.addCallParam("value", 0);
        digester.parse(new File("tester.xml"));
        System.out.println("string: " + read );
    }

    public void readString(String a) {
        this.read = a;
    }
}

tester.xml:

<?xml version="1.0" encoding="UTF-8"?>
<value>value1</value>

Upvotes: 0

Related Questions