2

在使用 SimpleXml 生成 XML 文件时,我遇到了挑战问题。

我想通过以下方式进行动态 xml 输出。

<process>
<sequence> ... </sequence>
<flow> ... </flow>
<sequence> ... </sequence>
<flow> ... </flow>
</process>

问题是如何使用 SimpleXMl 在 Schema 中定义?

现在,它看起来是这样的

@Root
public class Process {


    @ElementList(inline=true, required = false)
    private List<Sequences> sequence;

    @ElementList(inline=true, required = false)
    private List<Flows> flow;
    }

根据这个模式,它总是生成以下格式的 XML:

<process>
<sequence> ... </sequence>
<sequence> ... </sequence>
<flow> ... </flow>
<flow> ... </flow>
</process>

我该怎么办?谢谢你。

4

1 回答 1

2

这是您需要从文档中使用的方式:

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#scatter

祝你好运。


分散内联元素条目

散布在整个 XML 文档中的元素可以通过内联列表和内联映射来收集。只需为列表或映射要收集的 XML 元素名称提供条目名称,它们将被提取并放入集合对象中。例如,采用以下 XML 元素。它包含没有特定顺序的包含和排除 XML 元素。即使它们没有任何顺序,反序列化过程也能够收集遇到的 XML 元素。

<fileSet path="/user/niall">
   <include pattern=".*.jar"/>
   <exclude pattern=".*.bak"/>
   <exclude pattern="~.*"/>
   <include pattern=".*.class"/>
   <exclude pattern="images/.*"/>
</fileSet>

为了实现这一点,可以使用以下目标。这声明了两个内联集合,它们指定了它们正在收集的条目对象的名称。如果未指定 entry 属性,则将使用对象的名称。

@Root
public class FileSet {

   @ElementList(entry="include", inline=true)
   private List<Match> include;

   @ElementList(entry="exclude", inline=true)
   private List<Match> exclude;

   @Attribute
   private File path;

   private List<File> files;

   public FileSet() {
      this.files = new ArrayList<File>();
   }

   @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<File> 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);         
      }         
   }
}
于 2011-11-11T15:51:17.700 回答