2017-02-22 120 views
0

我有屬性文件,其中有2個xml文件中的名稱標籤的鍵值,其中一個是源,另一個是目標。在JAVA中將一個xml文件中的內容添加到另一個文件中

我需要檢查屬性文件中是否有相同值的名稱標記存在或不存在於目標xml中,如果存在,我不應該執行任何操作,如果沒有,則應該迭代源xml文件以搜索名稱標籤值來自屬性文件。一旦它發現了相同名稱的標籤應該從source.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

destination.xml

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

第一步:這需要文件1 '高清' 的從屬性文件密鑰值,並檢查在destination.xml文件,因爲它不存在它會追加它。

第2步:它從屬性文件中獲取文件2'xyz'值的下一個鍵值並檢查destination.xml文件,因爲它不存在它將附加它。

第3步:它從屬性文件中獲取文件3'abc'的下一個鍵值並在destination.xml中進行檢查,因爲它在那裏不會被附加。

而且現在​​應該是什麼樣子,

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

這是我的要求在JAVA做的,我已經試過編碼的很多。

請幫我解決這個問題..

回答

0

你快到了。

您正在做的錯誤是使用內部3級嵌套for-loop,而只需要2級嵌套for-loop。

listSrc的for-loop應位於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(); 

     } 
    } 
} 
+0

非常感謝兄弟,這是完美的代碼更改你指出,而不是使用嵌套for循環, – Jeelan

相關問題