QingKeZhiXia
8/13/2019 - 9:29 AM

Apache Commons Digester

Apache Commons Digester

import org.apache.commons.digester3.Digester;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.ArrayList;
import java.util.List;

public class ApacheCommonsDigester {
    private Foo foo;

    public void setFoo(Foo foo) {
        this.foo = foo;
    }

    public static void main(String[] args) throws IOException, SAXException {
        Main main = new Main();

        Digester digester = new Digester();
        digester.setValidating(false);

        digester.push(main);

        digester.addObjectCreate("foo", Foo.class);
        digester.addSetProperties("foo", "name", "name");
        digester.addSetNext("foo", "setFoo");

        digester.addObjectCreate("foo/bar", Bar.class);
        digester.addSetProperties("foo/bar", new String[]{"id", "title"}, new String[]{"id", "name"});
        digester.addSetNext("foo/bar", "addBar", Bar.class.getSimpleName());

        Object parse = null;
        try (InputStream stream = Main.class.getClassLoader().getResourceAsStream("test.xml")) {
            parse = digester.parse(Objects.requireNonNull(stream));
        } catch (NullPointerException e) {
            return;
        }
//        Foo foo = (Foo) parse;
//        System.out.println(parse);

        System.out.println("MAIN: " + main.foo);
    }
}

class Foo {
    private String name;

    private List<Bar> barList;

    public Foo() {
        this.barList = new ArrayList<>();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println(this + "执行 setName 方法");
        this.name = name;
    }

    public void addBar(Bar bar) {
        System.out.println(this + "执行 addBar 方法");
        this.barList.add(bar);
    }

    @Override
    public String toString() {
        return "Foo{" +
                "name='" + name + '\'' +
                ", barList=" + barList +
                '}';
    }
}

class Bar {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        System.out.println(this + "执行 setId 方法");
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println(this + "执行 setName 方法");
        this.name = name;
    }

    @Override
    public String toString() {
        return "Bar{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
<foo name="The Parent">
    <bar id="123" title="The First Child" />
    <bar id="456" title="The Second Child" />
</foo>