比较两组XML数据而不将所有比较数据加载到内存中

时间:2014-10-06 20:33:18

标签: java xml algorithm comparison sax

所以我有两个XML文件正在被解析以获取信息。我正在尝试一种方法来确定其他XML文件中缺少一个XML文件中的哪些元素。现在,目前两个XML文件的结果都被加载到两个不同的数组中,但这并不好,因为要保留很多数据。

我需要以某种方式找出一个文件中缺少的内容而不将所有数据永久加载到内存中,因为有问题的XML文件可能非常大。

以下是xml的示例。想象一下,另一个文件缺少其中一个弱点。我已经在使用SAX解析器来获取实际数据了。

 <weaknesses>
   <wakness status="new" severity="low" id="14876">
     <cwe id="133" href="http://cwevis.org">Title1</cwe>
       <tool code="STRING" category="PERFORMANCE" name="aaa"/>
        <rule name="Method invokes inefficient new String(String) constructor"/>
         <locations>
         <location path="Catcher.java" type="file">
         <line end="93" start="93"/>
          <description>stuff</description>
         </location>
         </locations>
    </weakness>

   <weakness status="new" severity="low" id="14877">
     <cwe id="138" href="http://cwevis.org">Title2</cwe>
       <tool code="PARAMETER" category="SECURITY" name="bbb"/>
        <rule name="Servlet parameters unsafe"/>
         <locations>
          <location path="Catcher.java" type="file">
         </locations>
   </weakness>

   <weakness status="new" severity="low" id="14878">
     <cwe id="500" href="http://cwevis.org">Title3</cwe>
       <tool code="FINAL" category="asd" name="vvv"/>
         <rule name="Field isn't final and can't be protected from malicious code"/>
          <locations>
           <location path="Course.java" type="file">
           <line end="56" start="56"/>
           <description>stuff </description>
           </location>
          </locations>
   </weakness>
 </weaknesses>

注意:我正在用Java编程,并假设元素没有排序。我想到的两个想法是加载两个集合并将一个集合与另一个集合进行比较的简单方法,这些集合可以解决内存问题。另一个是在不存储东西的情况下反复解析xml,但其过程效率很低。

1 个答案:

答案 0 :(得分:2)

让我们假设您将xmlfile A与B进行比较。在解析文件A时,首先用所有A元素填充集合X;当您解析文件B时,您尝试从堆栈X中删除您找到的任何元素。如果你得到true(它已从集合中移除),那么你继续。如果得到false(它不在集合X中),则将其保存在集合Y中。在解析文件B的最后,堆栈X将包含A中的所有元素而不包含在B中;堆栈Y将包含B中不在A中的所有元素。

这要求你实现一个实现弱对象的实体类,它实现equals(用于remove调用工作),最后是Comparable接口(一个有序的集合可能更适合对于这个问题的某些方面)。