在JAVA中将内容从一个xml文件添加到另一个xml文件

在JAVA中将内容从一个xml文件添加到另一个xml文件,java,xml,xml-parsing,Java,Xml,Xml Parsing,我有一个属性文件,在2个xml文件中有name-tag的键值,一个是源文件,另一个是目标文件 我需要检查目标xml中是否存在与属性文件中的值相同的名称标记,如果存在,我不应该做任何事情,如果不存在,则应迭代源xml文件以搜索属性文件中的名称标记值。一旦找到相同的名称标记,就应该将其从source.xml文件添加到destination.xml文件中 请在这个java代码上帮助我 private void updateCofigDestn() throws ParserConfigurationE

我有一个属性文件,在2个
xml
文件中有name-tag的键值,一个是源文件,另一个是目标文件

我需要检查目标xml中是否存在与属性文件中的值相同的名称标记,如果存在,我不应该做任何事情,如果不存在,则应迭代源xml文件以搜索属性文件中的名称标记值。一旦找到相同的名称标记,就应该将其从
source.xml
文件添加到
destination.xml
文件中

请在这个java代码上帮助我

private void updateCofigDestn() throws ParserConfigurationException, TransformerConfigurationException, TransformerException, IOException, SAXException {
    prop = loadConfigProperties();
    String ConfigSrcFile = prop.getProperty("ConfigSourceFile");
    String ConfigDesnFile = prop.getProperty("ConfigDestnFile");
    System.out.println("\nConfig  Destn Path update config :: " + ConfigDesnFile);
    File configSrcFile = new File(ConfigSrcFile + "\\config.xml");
    File configDstnFile = new File(ConfigDesnFile + "\\config.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setValidating(false);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document docSrc = dBuilder.parse(configSrcFile);
    Document docDestn = dBuilder.parse(configDstnFile);

    Set < Object > keys = getAllKeys();
    for (Object k: keys) {
        if (k.toString().startsWith("JDBC")) {
            System.out.println("Inside Keys");
            String key = (String) k;
            keyVal = getPropertyValue(key);
            System.out.println(key + ": " + getPropertyValue(key));


            NodeList listSrc =
                docSrc.getElementsByTagName("jdbc-system-resource");
            NodeList listDsn =
                docDestn.getElementsByTagName("jdbc-system-resource");
            System.out.println("listDsn.item(0)" + listDsn.item(0).getTextContent());

            if (listDsn.item(0) != null) {

                for (int t = 0; t < listDsn.getLength(); t++) {
                    Element elmntDsn1 = (Element) listDsn.item(t);
                    String DsNameDsn1 = elmntDsn1.getElementsByTagName("name").item(0).getTextContent();
                    System.out.println("DS At DESTN in Update Conf  " + DsNameDsn1);

                    if (keyVal.equalsIgnoreCase(DsNameDsn1)) {} else {

                        for (int temp = 0; temp < listSrc.getLength(); temp++) {
                            Element elmntSrc = (Element) listSrc.item(temp);
                            String DsNameSrc = elmntSrc.getElementsByTagName("name").item(0).getTextContent();
                            //  elmntSrc.getElementsByTagName(keyVal).item(0).getTextContent();

                            // configDestn(keyVal);
                            //System.out.println("value bool >>>>> " +res ) ;

                            if (keyVal.equalsIgnoreCase(DsNameSrc) && keyVal != null) {

                                Node copiedNode = docDestn.importNode(elmntSrc, true);
                                docDestn.getDocumentElement().appendChild(copiedNode);
                                System.out.println(" Updating the destination Config File");
                                TransformerFactory.newInstance().newTransformer().transform(new DOMSource(docDestn),
                                    new StreamResult(new FileWriter(configDstnFile)));
                            }
                        }

                    }
                }
            } else {
                System.out.println("Destination List is null ");
                for (int temp = 0; temp < listSrc.getLength(); temp++) {

                    Element elmntSrc = (Element) listSrc.item(temp);
                    String elmntValSrc = elmntSrc.getElementsByTagName("name").item(0).getTextContent();
                    if (keyVal.equalsIgnoreCase(elmntValSrc) &&
                        keyVal != null) {
                        Node copiedNode = docDestn.importNode(elmntSrc, true);
                        docDestn.getDocumentElement().appendChild(copiedNode);
                        System.out.println(" Updating the destination Config File in NULL");
                        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(docDestn),
                            new StreamResult(new FileWriter(configDstnFile)));
                    }
                }
            }
        }
    }
}
source.xml

<domain>
    <node0>
        <name>xyz</name>
    </node0>
    <node1>
        <name>abc</name>
    </node1>
    <node2>
        <name>def</name>
    </node2>
</domain>
这是我在JAVA中的要求,我已经尝试了很多编码

请帮我解决这个问题。

你就快到了

您所犯的错误是使用内部3级嵌套for循环,而只需要2级嵌套for循环

listSrc
的for循环应该在
destSrc
之外

试试下面这个

package com.tmp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Properties;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

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

public class Tmp {

    public static void main( String[] args ) {

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            XPath path = XPathFactory.newInstance().newXPath();

            Document destDocument = builder.parse( new FileInputStream( "D:\\tmp\\destination.xml" ) );
            Document srcDocument = builder.parse( new FileInputStream( "D:\\tmp\\source.xml" ) );

            Element destRootEle = destDocument.getDocumentElement();
            Element srcRootEle = srcDocument.getDocumentElement();

            Properties properties = new Properties();

            properties.load( new FileInputStream( "D:\\tmp\\config.properties" ) );

            // read properties from config.properties file one by one
            for ( Map.Entry<Object, Object> entry : properties.entrySet() ) {

                String propVal = (String) entry.getValue();

                NodeList destNodeList = (NodeList) path.evaluate( "//name", destRootEle, XPathConstants.NODESET );

                boolean destNodeNotExist = true;

                // iterate through the destination.xml to check whether property value is exist or not
                for ( int i = 0; i < destNodeList.getLength(); i++ ) {

                    Node node = destNodeList.item( i );

                    if ( propVal.trim().equals( node.getTextContent().trim() ) ) {

                        destNodeNotExist = false;

                        break;
                    }
                }


                // if the property value is not found in destination.xml then check for the node in source.xml to add to the destination.xml
                if ( destNodeNotExist ) {

                    NodeList srcNodeList = (NodeList) path.evaluate( "//name", srcRootEle, XPathConstants.NODESET );

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

                        Node missingNodeToAdd = srcNodeList.item( i );

                        if ( propVal.trim().equals( missingNodeToAdd.getTextContent().trim() ) ) {

                            destRootEle.appendChild( destDocument.adoptNode( missingNodeToAdd.getParentNode() ) );

                            break;
                        }
                    }
                }
            }

            // save the changes made to destination.xml file into file system
            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.setOutputProperty( OutputKeys.INDENT, "yes" );
            tr.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
            tr.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
            tr.transform( new DOMSource( destDocument ), new StreamResult( new FileOutputStream( "D:\\tmp\\destination.xml" ) ) );

        } catch ( Exception e ) {

            e.printStackTrace();

        }
    }
}
package com.tmp;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.util.Map;
导入java.util.Properties;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.transform.OutputKeys;
导入javax.xml.transform.Transformer;
导入javax.xml.transform.TransformerFactory;
导入javax.xml.transform.dom.DOMSource;
导入javax.xml.transform.stream.StreamResult;
导入javax.xml.xpath.xpath;
导入javax.xml.xpath.XPathConstants;
导入javax.xml.xpath.XPathFactory;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
公共级Tmp{
公共静态void main(字符串[]args){
DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
试一试{
DocumentBuilder=builderFactory.newDocumentBuilder();
XPath路径=XPathFactory.newInstance().newXPath();
Document destDocument=builder.parse(新文件输入流(“D:\\tmp\\destination.xml”);
Document srcDocument=builder.parse(新文件输入流(“D:\\tmp\\source.xml”);
Element destRootEle=destDocument.getDocumentElement();
元素srcRootEle=srcDocument.getDocumentElement();
属性=新属性();
加载(新文件输入流(“D:\\tmp\\config.properties”);
//逐个从config.properties文件读取属性
for(Map.Entry:properties.entrySet()){
String propVal=(String)entry.getValue();
NodeList destNodeList=(NodeList)path.evaluate(“//name”,destRootEle,XPathConstants.NODESET);
布尔destNodeNotExist=true;
//迭代destination.xml以检查属性值是否存在
对于(int i=0;i
非常感谢兄弟,这是你指出的完美代码更改,而不是使用嵌套for循环,
<domain>
    <node1>
        <name>abc</name>
    </node1>
</domain>
<domain>
    <node1>
        <name>abc</name>
    </node1>
    <node0>
        <name>xyz</name>
    </node0>
    <node2>
        <name>def</name>
    </node2>
</domain>
package com.tmp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Properties;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

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

public class Tmp {

    public static void main( String[] args ) {

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            XPath path = XPathFactory.newInstance().newXPath();

            Document destDocument = builder.parse( new FileInputStream( "D:\\tmp\\destination.xml" ) );
            Document srcDocument = builder.parse( new FileInputStream( "D:\\tmp\\source.xml" ) );

            Element destRootEle = destDocument.getDocumentElement();
            Element srcRootEle = srcDocument.getDocumentElement();

            Properties properties = new Properties();

            properties.load( new FileInputStream( "D:\\tmp\\config.properties" ) );

            // read properties from config.properties file one by one
            for ( Map.Entry<Object, Object> entry : properties.entrySet() ) {

                String propVal = (String) entry.getValue();

                NodeList destNodeList = (NodeList) path.evaluate( "//name", destRootEle, XPathConstants.NODESET );

                boolean destNodeNotExist = true;

                // iterate through the destination.xml to check whether property value is exist or not
                for ( int i = 0; i < destNodeList.getLength(); i++ ) {

                    Node node = destNodeList.item( i );

                    if ( propVal.trim().equals( node.getTextContent().trim() ) ) {

                        destNodeNotExist = false;

                        break;
                    }
                }


                // if the property value is not found in destination.xml then check for the node in source.xml to add to the destination.xml
                if ( destNodeNotExist ) {

                    NodeList srcNodeList = (NodeList) path.evaluate( "//name", srcRootEle, XPathConstants.NODESET );

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

                        Node missingNodeToAdd = srcNodeList.item( i );

                        if ( propVal.trim().equals( missingNodeToAdd.getTextContent().trim() ) ) {

                            destRootEle.appendChild( destDocument.adoptNode( missingNodeToAdd.getParentNode() ) );

                            break;
                        }
                    }
                }
            }

            // save the changes made to destination.xml file into file system
            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.setOutputProperty( OutputKeys.INDENT, "yes" );
            tr.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
            tr.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
            tr.transform( new DOMSource( destDocument ), new StreamResult( new FileOutputStream( "D:\\tmp\\destination.xml" ) ) );

        } catch ( Exception e ) {

            e.printStackTrace();

        }
    }
}