散布内联元素条目
可以通过内联列表和内联映射收集分散在整个XML文档中的元素。只需提供列表或映射要收集的XML元素名称的条目名称,它们将被提取并放入集合对象中。例如,使用以下XML元素。它包含不包含特定顺序的包含和排除XML元素。即使它们不是任何顺序,反序列化过程也能够在遇到时收集XML元素。
为了实现这一点,可以使用以下目的。这声明了两个内联集合,它们指定了它们正在收集的条目对象的名称。如果未指定entry属性,则将使用该对象的名称。
@Root
public class FileSet {
@ElementList(entry="include", inline=true)
private List include;
@ElementList(entry="exclude", inline=true)
private List exclude;
@Attribute
private File path;
private List files;
public FileSet() {
this.files = new ArrayList();
}
@Commit
public void commit() {
scan(path);
}
private void scan(File path) {
File[] list = path.listFiles();
for(File file : list) {
if(file.isDirectory()) {
scan(path);
} else {
if(matches(file)) {
files.add(file);
}
}
}
}
private boolean matches(File file) {
for(Match match : exclude) {
if(match.matches(file)) {
return false;
}
}
for(Match match : include) {
if(match.matches(file)) {
return true;
}
}
return false;
}
public List getFiles() {
return files;
}
@Root
private static class Match {
@Attribute
private String pattern;
public boolean matches(File file) {
Stirng path = file.getPath();
if(!file.isFile()) {
return false;
}
return path.matches(pattern);
}
}
}