合并在NodeList上循环的2个XML文件

时间:2015-07-07 09:26:34

标签: java xml

我有2个xml文件..要合并到1个xml文件中

输入文件:

reference.xml

<company>
    <staff>
        <name>
            <surname>smith </surname>
        </name>
        <phone>465456433</phone>
        <email>gmail1</email>
    </staff>
</company>

comparison.xml

<company>
    <staff>
        <name>
            <initials>js</initials>
        </name>
        <area>area1</area>
        <city>city1</city>
    </staff>
</company>

预期产出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <staff>
        <name>
             <surname>smith</surname>
             <initials>js</initials>
        </name>
        <phone>465456433</phone>
        <email>gmail1</email>
        <area>area1</area>
        <city>city1</city>
     </staff>
</company>

我通过获取标记名称来获取具有硬编码代码的输出。但是有没有办法循环每个父节点并从2个文件导入其子节点而不将标记标记为GENERIC

public class merge {

 public static void main(String[] args) {



    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    Document doc = null;
    Document doc2 = null;

    try {

        ///////////////////////////////////////////////////////////////////////

            db = dbf.newDocumentBuilder();
            doc = db.parse(new File("C:/Users/IBM_ADMIN/Desktop/reference.xml"));
            doc2 = db.parse(new File("C:/Users/IBM_ADMIN/Desktop/comparison.xml"));

            NodeList ndListFirstFile = doc.getElementsByTagName("staff");


            Node nodeArea = doc.importNode(doc2.getElementsByTagName("area").item(0), true);
            Node nodeCity = doc.importNode(doc2.getElementsByTagName("city").item(0), true);
            ndListFirstFile.item(0).appendChild(nodeArea);
            ndListFirstFile.item(0).appendChild(nodeCity);


      NodeList ndList = doc.getElementsByTagName("name");

            Node nodesur =    doc.importNode(doc.getElementsByTagName("surname").item(0), true);
            Node nodein = doc.importNode(doc2.getElementsByTagName("initials").item(0), true);
            ndList.item(0).appendChild(nodesur);
            ndList.item(0).appendChild(nodein);


         ///////////////////////////////////////////////////////////////////
          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.INDENT, "yes");  

          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(new StringWriter());
          transformer.transform(source, result); 

          Writer output = new BufferedWriter(new FileWriter("C:/Users/IBM_ADMIN/Desktop/final.xml"));
          String xmlOutput = result.getWriter().toString();  
          output.write(xmlOutput);
          output.close();

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


  }

}

由于

1 个答案:

答案 0 :(得分:1)

您可以使用

NodeList list = doc.getChildNodes();

但是你必须检查每个孩子以确认它是一个元素。

for (int i = 0; i < list.getLength(); ++i)
{
    Node n = list.item(i);
    if (n.getType().equals(Node.ELEMENT_NODE))
    {
        n.getNodeName();
    }
}

这样的事情。要处理文档中的所有元素,您必须使用广度/深度优先算法。

Stack<Node> pending = new Stack<Node>();
pending.push(doc.getChildNodes().item(0));
while(!pending.empty())
{
   Node n = pending.pop();
   n.getChildNodes();
   ...
}

应该清楚如何继续前进。如果没有,我会在有空的时候制定一个更有效的版本。