Method 1: Dom4J processes XMLimportjava. io. file; importjava. io. fileInputStream; importjava. io. fileNotFoundException; importjava. io. fileWriter; importjava. io. IOException; importjava. io. inputStream; importor
Method 1: Dom4J handles XML
Import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileWriter; import java. io. IOException; import java. io. inputStream; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; import org. dom4j. io. XMLWriter; * combines and outputs 2 xml documents, the jar: dom4j-1.6.1.jar required, the jaxen-1.1.1.jar * inserts all content at the upper-level or lower-level of a tag of an xml document to another Under a tag of an xml document * @ date 2011-04-13 * @ author RobotJi * @ version 1.0 public class UniteXML {public UniteXML () {}* get doc according to is, here the is can be a local stream or a network stream * @ param is * @ return public static Document getDocument (InputStream is) {Document doc = null; try {doc = new SAXReader (). read (is);} catch (incluentexception e) {e. printStackTrace ();} return doc;} public static InputStream getInputStream (String path) {File f = New File (path); if (! F. exists () {return null;} InputStream is = null; try {is = new FileInputStream (f);} catch (FileNotFoundException e) {e. printStackTrace ();} return is;} * get the sub-Element * @ param doc the Document to be obtained * @ param tagName the tag corresponding to the Document * @ return public Element getSubElement (Document doc, string tagName) {Element el = (Element) doc. selectSingleNode ("//" + tagName); return el;} * output xml Document * @ param doc file to be output * @ param fileName path public void writeXML (Document doc, string fileName) {try {XMLWriter writer = new XMLWriter (new FileWriter (fileName); writer. write (doc); writer. flush (); writer. close ();} catch (IOException e) {e. printStackTrace ();}} * merge doc * @ param path1 main document * @ param path2 the merged document * @ param tagName1 the tag to be inserted in the main document * @ param tagName2 the tag of the merged document * @ param isContain whether to include all nodes under the top-level tag of the merged Document * @ return public Document unitXMl (String path1, string path2, String tagName1, String tagName2, boolean isContain) {Document doc1 = getDocument (getInputStream (path1); Document doc2 = getDocument (getInputStream (path2 )); element elSub2 = getSubElement (doc2, tagName2); Element elSub1 = getSubElement (doc1, tagName1); if (isContain) {// doc1.getRootElement (). appendContent (elSub2.getParent (); // Insert elSub1.appendContent (elSub2.getParent () under the root tag; // Insert it to the tagName1 tag} else {// doc1.getRootElement (). appendContent (elSub2); elSub1.appendContent (elSub2);} return doc1;} public static void main (String [] args) {UniteXML ux = new UniteXML (); // Insert all content under the c tag to the aa tag. if the parameter is set to true, you can insert all content under the upper and lower levels of the c tag to the Document doc = ux under the aa tag. unitXMl ("F: \ test \. xml "," F: \ test \ B. xml "," aa "," c ", false); ux. writeXML (doc, "F: \ test \ a_test.xml ");}}
// The two xml files used for the test are as follows:
A. xml
Method 2:
Import java. io. *; // basic Java package, including various IO operations import java. util. *; // basic Java package, including various standard data structure operations import javax. xml. parsers. *; // XML parser interface import org. w3c. dom. *; // xml dom implementation import javax. xml. transform. *; import javax. xml. transform. dom. *; import javax. xml. transform. stream. *;/*** XML file merging tool class * @ author GhostFromHeaven */public class XMLMergeUtil {/*** XML file merging and processing * @ param mainFileName xml file to be merged and processed, this file will be updated after merging * @ pa The xml file whose ram subFilename is merged * @ return returns true if the merge is successful; otherwise, false * @ throws Exception */public static boolean isMerging (String mainFileName, String subFilename) is returned) throws Exception {DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); DocumentBuilder db = null; try {db = dbf. newDocumentBuilder ();} catch (ParserConfigurationException pce) {System. err. println (pce); // output exception information when an exception occurs} Document Doc_main = null; Document doc_vice = null; // obtain the Document try {doc_main = db for two XML files. parse (mainFileName); doc_vice = db. parse (subFilename);} catch (DOMException dom) {System. err. println (dom. getMessage ();} catch (Exception ioe) {System. err. println (ioe);} // Obtain the root node of the two files. Element root_main = doc_main.getDocumentElement (); Element root_vice = doc_vice.getDocumentElement (); // add No for each node under the root node of the merged file below DeList messageItems = root_vice.getChildNodes (); int item_number = messageItems. getLength (); // if the first node under the root node is removed, I starts from 3; otherwise, I starts from 1 for (int I = 1; I <item_number; I = I + 2) {// call dupliate () and copy the Element messageItem = (Element) messageItems under the root node in the merged XML file in sequence. item (I); dupliate (doc_main, root_main, messageItem);} // call write To () To write the merged Document To the target XML Document boolean isWritten = writeTo (doc_main, mainFileNam E); return isWritten;}/***** @ param doc_dup * @ param father * @ param son * @ return * @ throws Exception */private static boolean dupliate (Document doc_dup, element father, Element son) throws Exception {boolean isdone = false; Element parentElement = null; DuplicateChildElementObject childElementObject = isChildElement (father, son); if (! ChildElementObject. isNeedDuplicate () {// the same node does not need to be merged isdone = true; parentElement = childElementObject. getElement ();} else if (childElementObject. getElement ()! = Null) {parentElement = childElementObject. getElement () ;}else {parentElement = father;} String son_name = son. getNodeName (); Element subITEM = null; if (! Isdone) {subITEM = doc_dup.createElement (son_name); // Copy the attributes of the node if (son. hasAttributes () {NamedNodeMap attributes = son. getAttributes (); for (int I = 0; I <attributes. getLength (); I ++) {String attribute_name = attributes. item (I ). getNodeName (); String attribute_value = attributes. item (I ). getNodeValue (); subITEM. setAttribute (attribute_name, attribute_value) ;}} parentElement. appendChild (subITEM );} Else {subITEM = parentElement;} // Copy the subnode NodeList sub_messageItems = son. getChildNodes (); int sub_item_number = sub_messageItems.getLength (); if (sub_item_number <2) {// if no subnode exists, isdone = true is returned ;} else {for (int j = 1; j <sub_item_number; j = j + 2) {// if a subnode exists, recursively call this method Element sub_messageItem = (Element) sub_messageItems.item (j); isdone = dupliate (doc_dup, subITEM, sub_messageItem );}} Return isdone;} private static boolean writeTo (Document doc, String fileName) throws Exception {boolean isOver = false; DOMSource doms = new DOMSource (doc ); file f = new File (fileName); StreamResult sr = new StreamResult (f); try {TransformerFactory tf = TransformerFactory. newInstance (); Transformer t = tf. newTransformer (); Properties properties = t. getOutputProperties (); properties. setProperty (OutputKeys. ENCODING, "UTF-8"); t. setOutputProperties (properties); t. transform (doms, sr); isOver = true;} catch (TransformerConfigurationException tce) {tce. printStackTrace ();} catch (TransformerException te) {te. printStackTrace ();} return isOver;} private static DuplicateChildElementObject isChildElement (Element father, Element son) {DuplicateChildElementObject childElementObject = new Dupli CateChildElementObject (); NodeList messageItems = father. getChildNodes (); int item_number = messageItems. getLength (); // first, traverse all nodes to check whether there are identical nodes. This prevents the same node from being defined for multiple times (int I = 1; I <item_number; I = I + 2) {Element messageItem = (Element) messageItems. item (I); if (! MessageItem. getNodeName (). equals (son. getNodeName () {continue;} if (messageItem. isEqualNode (son) {// Determine whether the child nodes are consistent with childElementObject. setNeedDuplicate (false); childElementObject. setElement (messageItem); return childElementObject ;}}for (int I = 1; I <item_number; I = I + 2) {Element messageItem = (Element) messageItems. item (I); // determines whether the node is at the same level if (! MessageItem. getNodeName (). equals (son. getNodeName () {continue;} if (isw.node (messageItem, son) {// only judge whether the current node is consistent if (has#attributes (messageItem, son )) {// the current node is completely the same and does not need to be merged into childElementObject. setNeedDuplicate (false); childElementObject. setElement (messageItem); return childElementObject;} else {// attributes of the current node are different, and childElementObject needs to be merged. setNeedDuplicate (true); childElementObject. setElement (father); return chil DElementObject ;}}// this node does not exist in the Target document. you need to merge it into the Target document childElementObject. setNeedDuplicate (true); childElementObject. setElement (father); return childElementObject;}/*** checks whether the two nodes are the same, unjudge Node attributes * @ param arg0 * @ param arg * @ return */private static boolean isw.node (Node arg0, Node arg) {if (arg = arg0) {return true;} if (arg. getNodeType ()! = Arg0.getNodeType () {return false;} if (arg0.getNodeName () = null) {if (arg. getNodeName ()! = Null) {return false ;}} else if (! Arg0.getNodeName (). equals (arg. getNodeName () {return false;} if (arg0.getLocalName () = null) {if (arg. getLocalName ()! = Null) {return false ;}} else if (! Arg0.getLocalName (). equals (arg. getLocalName () {return false;} if (arg0.getNamespaceURI () = null) {if (arg. getNamespaceURI ()! = Null) {return false ;}} else if (! Arg0.getNamespaceURI (). equals (arg. getNamespaceURI () {return false;} if (arg0.getPrefix () = null) {if (arg. getPrefix ()! = Null) {return false ;}} else if (! Arg0.getPrefix (). equals (arg. getPrefix () {return false;} if (arg0.getNodeValue () = null) {if (arg. getNodeValue ()! = Null) {return false ;}} else if (! Arg0.getNodeValue (). equals (arg. getNodeValue () {return false;} return true ;} /*** determine whether the Node attributes are the same * @ param arg0 * @ param arg * @ return */private static boolean hasEqualAttributes (Node arg0, Node arg) {NamedNodeMap map1 = arg0.getAttributes (); NamedNodeMap map2 = arg. getAttributes (); int len = map1.getLength (); if (len! = Map2.getLength () {return false;} for (int I = 0; I <len; I ++) {Node n1 = map1.item (I); if (n1.getNodeName ()! = Null) {Node n2 = map2.getNamedItem (n1.getNodeName (); if (n2 = null) {return false;} else if (! N1.getNodeValue (). equals (n2.getNodeValue () {return false ;}} return true;} public static void main (String [] args) {try {String sourcefile = "d:/. xml "; String targetfile =" d:/B. xml "; boolean isdone = XMLMergeUtil. isMerging (sourcefile, targetfile); if (isdone) System. out. println ("XML files have been merged. "); else System. out. println ("XML files have NOT been merged. ");} catch (Exception e) {e. printStackTrace () ;}}/ *** copy the subnode object * @ author Administrator **/class DuplicateChildElementObject {private boolean needDuplicate = true; // record whether the node needs to copy private Element element = null; // record the parent node of the node public DuplicateChildElementObject () {super ();} public boolean isNeedDuplicate () {return needDuplicate;} public void setNeedDuplicate (boolean needDuplicate) {this. needDuplicate = needDuplicate;} public Element getElement () {return element;} public void setElement (Element element) {this. element = element ;}}
The above is a detailed description of the two Xml merge instances in Android development. For more information, see other related articles in the first PHP community!