0

我正在使用apache.commons.digester处理一个 xml 文件

例如,xml 的结构如下:

< Files >    
< File Name="ABC.EXE" Version="1.0" Size="3954174" >    
< File Name="XYZ.EXE" Version="2.0" Size="11833856" >    
< File Name="RST.exe" Version="3.0" Size="32768" >    
< Files >

我想避免在 Digester 解析 xml 后循环。有没有我可以指定的规则,以便我只返回与文件相关的属性name="XYZ.EXE'

更新 -

因为,我问了这个问题,我用谷歌搜索了一下,http ://wiki.apache.org/commons/Digester/FAQ 上面说单独使用 Digester,不能访问具有特定值的属性。需要使用 XSLT 转换 (org.xml.sax.XMLFilter)。我不知道该怎么做。仍在寻找解决方案。欢迎任何建议。

4

2 回答 2

1
digester.addRule("Files/File",new ConditionalCreationRule("XYZ.EXE"));

在条件创建规则(您创建的类)中,您可以执行此操作。让我知道这是否足够。

于 2010-03-04T14:15:22.747 回答
1

完整片段

public class Files {
    List<MyFile> list = new ArrayList<MyFile>();

    public Files() {
        super();
    }

    public boolean addFile(MyFile f) {
        return list.add(f);
    }
}

public class MyFile {
    public String name;
    public String version;
    public String size;
    public void setName(String name) {
        this.name = name;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public void setSize(String size) {
        this.size = size;
    }
    @Override
    public String toString() {
        return "MyFile [name=" + name + ", size=" + size + ", version="
                + version + "]";
    }

}

class ConditionalRule extends ObjectCreateRule {

    private boolean conditional = false;
    public ConditionalRule() throws ParserConfigurationException {
        super(MyFile.class);
    }

    @Override
    public void begin(String namespaceURI, String name, Attributes attributes)
            throws Exception {
        conditional = "ABC.EXE".equals(attributes.getValue("Name"));
        if(conditional) {
            Files files = (Files) digester.pop();
            MyFile f = new MyFile();
            files.addFile(f);
            digester.push(files);
            digester.push(f);
        }
    }

    @Override
    public void end() throws Exception {
        if(conditional) {
            digester.pop();
        }
    }

}
public class Snippet {

    @Test
    public void test() throws Exception {
        Digester d = new Digester();
        d.addObjectCreate("Files", Files.class);
        d.addRule("Files/File", new ConditionalRule());
        d.addSetProperties("Files/File",
                new String[]{"Name", "Version", "Size"}, new String[]{"name", "version", "size"});
        Object parse = d.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("digest.xml"));
        System.out.println(parse);
    }
}
于 2010-03-04T14:52:09.290 回答