0

我的 xml 就像<value>value1</value>我想使用 commons-digester 解析它并希望将“value1”作为字符串对象

4

2 回答 2

1

使用 Lukasz 的答案,如果您不想创建另一个对象来保存该值,那么您可以将 a 压入StringBuilder堆栈,然后调用appendusing addCallMethod。为了清楚起见,我在这里复制了代码:

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);
    }
}
于 2012-01-18T13:43:05.200 回答
0

我认为不可能将“value1”直接加载到String实例中(by addObjectCreate),因为 String 是不可变的。而不是这个,我会强制消化器调用一个方法。短样本:

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>
于 2011-04-29T12:00:29.297 回答