【问题标题】:How to parse two xml file and compare the specific elements of respective xml's in java?如何解析两个xml文件并比较java中各个xml的具体元素?
【发布时间】:2014-08-20 07:29:18
【问题描述】:

第一个 xml 文件 test_balance1.xml

第二个xml文件test_balance2.xml

如何使用 SAX 解析器解析两个 xml 文件并比较 java 中的特定元素?

例如:我需要解析

                line 12: <brm:CURRENT_BAL>-30</brm:CURRENT_BAL> 
                line 24: <brm:CURRENT_BAL>0</brm:CURRENT_BAL>  of test_balance1.xml and

                line 12: <brm:CURRENT_BAL>55</brm:CURRENT_BAL> 
                line 24: <brm:CURRENT_BAL>20</brm:CURRENT_BAL> of test_balance2.xml

解析后如何比较具体元素,即 CURRENT_BAL= -30 和 CURRENT_BAL=55 ,还有 CURRENT_BAL=0 和 CURRENT_BAL=20

【问题讨论】:

    标签: java xml parsing


    【解决方案1】:

    您可以在此处使用 XMLUtils + 参考答案:Best way to compare 2 XML documents in Java

    import oracle.xml.diff.XmlUtils;
    import oracle.xml.diff.Options;
    
    import java.io.File;
    
    import org.w3c.dom.Node;
    import org.w3c.dom.Document;
    
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    
    public class textDiff
    {
        public static void main(String[] args) throws Exception
        {
            XmlUtils xmlUtils = new XmlUtils();
    
            //Parse the two input files
            DocumentBuilderFactory dbFactory =   
                      DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = 
                      dbFactory.newDocumentBuilder();
            Node doc = docBuilder.parse(new File(args[0]));
            Node doc1 = docBuilder.parse(new File(args[1]));
    
            //Run the diff
            try
            {
                Document diffAsDom = xmlUtils.diffToDoc(doc, 
                                      doc1, new Options());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2022-11-24
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多