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

时间:2017-02-22 07:32:46

标签: java xml xml-parsing

我的属性文件在2 xml个文件中包含名称标记的键值,一个是源文件,另一个是目标文件。

我需要检查属性文件中具有相同值的名称标签是否存在于目标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)));
                    }
                }
            }
        }
    }
}

对于前..

config.properties

file1 = def
file2 = xyz
file3 = abc

source.xml

<domain>
    <node0>
        <name>xyz</name>
    </node0>
    <node1>
        <name>abc</name>
    </node1>
    <node2>
        <name>def</name>
    </node2>
</domain>

destination.xml

<domain>
    <node1>
        <name>abc</name>
    </node1>
</domain>

Step1:它从属性文件获取文件1'def'的键值并检入destination.xml文件,因为它不存在它会附加它。

Step2:它从属性文件获取文件2'xyz'值的下一个键值并检入destination.xml文件,因为它不存在它将附加它。

Step3:它从属性文件获取文件3'abc'的下一个键值,并检查destination.xml与否,因为它不会附加。

现在destination.xml应该是,

<domain>
    <node1>
        <name>abc</name>
    </node1>
    <node0>
        <name>xyz</name>
    </node0>
    <node2>
        <name>def</name>
    </node2>
</domain>

这是我在JAVA中的要求,我尝试过很多编码。

请帮我解决这个问题..

1 个答案:

答案 0 :(得分:0)

你快到了。

你正在做的错误是使用内部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();

        }
    }
}