当前位置: 首页 > 知识库问答 >
问题:

使用 java NodeList 合并 xml 文件

程彭祖
2023-03-14

我正在尝试合并两个xml文件,如下所示,但我无法获得所需的输出,请帮助我,谢谢

Java代码:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();   
domFactory.setIgnoringComments(true);  
DocumentBuilder builder = domFactory.newDocumentBuilder();   
Document doc = builder.parse(new File("file1.xml"));   
Document doc1 = builder.parse(new File("file2.xml"));   

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

NodeList nodes1 = doc1.getElementsByTagName("staff");

for(int i=0;i<nodes1.getLength();i=i+1){  

Node n= (Node) doc.importNode(nodes1.item(i), true);  
nodes.item(i).getParentNode().appendChild(n);

}  

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

StreamResult result = new StreamResult(new StringWriter());  
DOMSource source = new DOMSource(doc);  
transformer.transform(source, result);  
Writer output = null;
output = new BufferedWriter(new FileWriter("mergedxml.xml"));

String xmlOutput = result.getWriter().toString();  
output.write(xmlOutput);
output.close();
System.out.println("merge complete");

文件1.xml

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
        </staff>
    </company>

File2.xml

    <company>
        <staff>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>

电流输出:

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
        </staff>
        <staff>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>

预期输出:

    <company>
        <staff>
            <name>john</name>
            <phone>465456433</phone>
            <email>gmail1</email>
            <area>area1</area>
            <city>city1</city>
        </staff>
    </company>

共有3个答案

孟意致
2023-03-14

问题是,您想将子元素附加到“staff”元素,但您实际做的是:

nodes.item(i).getParentNode().appendChild(n);

这意味着您正在寻找列表中某个“员工”节点的父节点,该节点是“公司”。因此,您将一个新的“员工”节点(从doc1导入的节点)附加到doc的“公司”节点

现在,您要做的是迭代doc1的“staff”子节点,并将它们逐个追加到doc的“staff”节点。因此,您可能希望将节点1的定义更改如下:

// Retrieving child nodes of first "staff" element of doc1
NodeList nodes1 = doc1.getElementsByTagName("staff").item(0).getChildNodes();

然后通过替换来更改附加到的节点

nodes.item(i).getParentNode().appendChild(n);

nodes.item(0).appendChild(n);

所以现在您将追加所有“staff”子节点(/!\仅适用于doc1的第一个“staff”元素)到doc的第一个“staff”元素

注1:不要使用迭代变量(i)来选择另一个列表的项目,除非你知道自己在做什么(例如,两个列表的长度相同)

注意2:该解决方案将把doc1的第一个“staff”元素的节点附加到doc的第一个”staff“元素。您可能需要在这里和那里添加一些迭代。

苏彦君
2023-03-14

此解决方案适用于在合并之前需要迭代和验证某些内容的文件。

file1.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <reactions>
        <reaction>
            <ID>07402</ID>
            <type>irreversible</type>
            <substrate>15666</substrate>
            <product>07756</product>
        </reaction>
        <reaction>
    <ID>03063</ID>
    <type>irreversible</type>
    <substrate>00916</substrate>
    <product>04712</product>
</reaction>

文件2.xml:

    <?xml version="1.0" encoding="UTF-8"?><reactions>
    <reaction>
        <ID>00001</ID>
        <reactionName>polyphosphate polyphosphohydrolase</reactionName>
        <reactionDescription> Polyphosphate + n H2O &lt;=&gt; (n+1) Oligophosphate</reactionDescription>
    </reaction>
    <reaction>
        <ID>00002</ID>
        <reactionName>Reduced ferredoxin:dinitrogen oxidoreductase (ATP-hydrolysing)</reactionName>
        <reactionDescription> 16 ATP + 16 H2O + 8 Reduced ferredoxin &lt;=&gt; 8 e- + 16 Orthophosphate + 16 ADP + 8 Oxidized ferredoxin</reactionDescription>
    </reaction>    
    <reaction>
        <ID>03063</ID>
        <reactionName>cephalosporin-C:2-oxoglutarate aminotransferase</reactionName>
        <reactionDescription> Cephalosporin C + 2-Oxoglutarate &lt;=&gt; (7R)-7-(5-Carboxy-5-oxopentanoyl)aminocephalosporinate + D-Glutamate</reactionDescription>
    </reaction>
    <reaction>
        <ID>07402</ID>
        <reactionName>(7R)-7-(4-carboxybutanamido)cephalosporanate amidohydrolase</reactionName>
        <reactionDescription> (7R)-7-(4-Carboxybutanamido)cephalosporanate + H2O &lt;=&gt; 7-Aminocephalosporanic acid + Glutarate</reactionDescription>
    </reaction>  
</reactions>

Result.xml

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<reactions>
    <reaction>
        <ID>07402</ID>
        <type>irreversible</type>
        <substrate>15666</substrate>
        <product>07756</product>
    <reactionName>(7R)-7-(4-carboxybutanamido)cephalosporanate amidohydrolase</reactionName>
<reactionDescription> (7R)-7-(4-Carboxybutanamido)cephalosporanate + H2O &lt;=&gt; 7-Aminocephalosporanic acid + Glutarate</reactionDescription>
</reaction>
    <reaction>
        <ID>03063</ID>
        <type>irreversible</type>
        <substrate>00916</substrate>
        <product>04712</product>
    <reactionName>cephalosporin-C:2-oxoglutarate aminotransferase</reactionName>
<reactionDescription> Cephalosporin C + 2-Oxoglutarate &lt;=&gt; (7R)-7-(5-Carboxy-5-oxopentanoyl)aminocephalosporinate + D-Glutamate</reactionDescription>
</reaction>
</reactions>

Java程序来做到这一点:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MergeXML {

    public static void main(String[] args) {
        MergeXML m = new MergeXML();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            DocumentBuilder db;

            db = dbf.newDocumentBuilder();

            Document secondaryMetabolismXML = db
                    .parse(new File("/home/bioinfo/workspace/teste/src/file1.xml"));
            Document generalMetabolismXML = db
                    .parse(new File("/home/bioinfo/workspace/teste/src/file2.xml"));

            NodeList secondaryReactions = secondaryMetabolismXML.getElementsByTagName("reaction");
            NodeList generalReactions = generalMetabolismXML.getElementsByTagName("reaction");

            for (int s = 0; s < secondaryReactions.getLength(); s++) {
                Node secondaryReaction = secondaryReactions.item(s);
                for (int g = 0; g < generalReactions.getLength(); g++) {
                    Node generalReaction = generalReactions.item(g);
                    if (getChildrenByNodeName(secondaryReaction, "ID").getTextContent()
                            .equals(getChildrenByNodeName(generalReaction, "ID").getTextContent())) {
                        if (getChildrenByNodeName(generalReaction, "reactionName") != null) {
                            secondaryReaction.appendChild(secondaryMetabolismXML
                                    .importNode(getChildrenByNodeName(generalReaction, "reactionName"), true));
                        }
                        if (getChildrenByNodeName(generalReaction, "reactionAlternativeName") != null) {
                            secondaryReaction.appendChild(secondaryMetabolismXML.importNode(
                                    getChildrenByNodeName(generalReaction, "reactionAlternativeName"), true));
                        }
                        if (getChildrenByNodeName(generalReaction, "reactionDescription") != null) {
                            secondaryReaction.appendChild(secondaryMetabolismXML
                                    .importNode(getChildrenByNodeName(generalReaction, "reactionDescription"), true));
                        }
                    }
                }
            }
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

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

            Writer output = new BufferedWriter(
                    new FileWriter("/home/bioinfo/workspace/teste/src/Result.xml"));
            String xmlOutput = result.getWriter().toString();
            output.write(xmlOutput);
            output.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Returns a node child when you have a match with a given node name
     * 
     * @param node
     * @param nodeName
     * @return
     */
    public static Node getChildrenByNodeName(Node node, String nodeName) {
        for (Node childNode = node.getFirstChild(); childNode != null;) {
            Node nextChild = childNode.getNextSibling();
            if (childNode.getNodeName().equalsIgnoreCase(nodeName)) {
                return childNode;
            }
            childNode = nextChild;
        }
        return null;
    }
}
公西光华
2023-03-14

为了自己做到这一点。您应该执行以下操作:

public static void mergeXML(){


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

    try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(new File("D:\\Loic_Workspace\\Test2\\res\\test.xml"));
            doc2 = db.parse(new File("D:\\Loic_Workspace\\Test2\\res\\test2.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);

          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("D:\\Loic_Workspace\\Test2\\res\\testFinal.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();
    }


}

testFinal.xml的最终产出:

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

如你所愿;-)

希望有帮助,

 类似资料:
  • 问题内容: 我正在尝试合并两个xml文件,如下所示,但我无法获得所需的输出,请帮助我,谢谢 Java代码: File1.xml File2.xml 电流输出: 预期产量: 问题答案: 为了自己做。您应该执行以下操作: testFinal.xml的最终输出: 如你所愿;-) 希望能帮助到你,

  • 问题内容: 我需要在xml的第三个块上合并两个xml文件。因此,文件A.xml和B.xml如下所示: A.xml B.xml 我需要合并“结果” 到目前为止,我所做的是: 如您所见,我将初始xml_element_tree分配给具有标题等的数据,然后使用“结果”扩展。但是,这给了我这个: 结果需要放在底部。任何帮助将不胜感激。 问题答案: 虽然这大部分是重复的,并且可以在这里找到答案,但我已经做到

  • 我有两个xml文件,需要使用XSLT将它们合并为一个。 第一个XML是(原始的): 第二个XML(更新数据)如下所示: 所需的合并结果-使用第二个XML更新第一个: 我已经搜索了stackoverflow,但仍然找不到答案。谢谢你的帮助。

  • 我正在尝试通过字符串将根数据合并为一个,但无法这样做。请帮助。

  • 问题内容: 我有2个文件,并且两个文件的结构相似,我想拥有一个。我尝试了许多解决方案,但只有错误-坦白地说,我不知道这些脚本是如何工作的。 : : 我想用以下结构创建一个新文件 我应该怎么做?你能解释一下方法吗?如何处理更多文件?谢谢 编辑 我尝试了什么? 编辑2 遵循Torious的建议,我查看了DOMDocument手册并找到了一个示例: 但是它创建了错误的xml文件: 而且我无法正确使用此文

  • 我有两个xml文件,需要将它们合并为一个xml。以下是示例: orginal.xml文件: 使现代化xml文件: 它们应合并为如下xml文件: 实际上,我想使用更新。xml来更新原始。xml: > update.xml中的新员工应该被添加到original.xml 在更新中修改了员工信息。xml应覆盖相应的员工节点。 我对XSLT略知一二,但我的知识还不足以找出适合合并的XSLT。