您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)Android開發(fā)中2個Xml合并的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
方法一:Dom4J處理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.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; * 合并并輸出2個xml文檔,所需要jar:dom4j-1.6.1.jar,jaxen-1.1.1.jar * 將某個xml文檔的某個標(biāo)簽下或該標(biāo)簽上一級下所有內(nèi)容插入到另一個xml文檔的某個標(biāo)簽下 * @date 2011-04-13 * @author RobotJi * @version 1.0 public class UniteXML { public UniteXML() {} * 根據(jù)is獲取doc,這里的is可以是本地流或者網(wǎng)絡(luò)流 * @param is * @return public static Document getDocument(InputStream is){ Document doc=null; try { doc=new SAXReader().read(is); } catch (DocumentException 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; } * 獲取子Element * @param doc 要獲取的文檔 * @param tagName 文檔對應(yīng)的標(biāo)簽 * @return public Element getSubElement(Document doc,String tagName){ Element el=(Element)doc.selectSingleNode("//"+tagName); return el; } * 輸出xml文檔 * @param doc 要輸出的文檔 * @param fileName 路徑 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(); } } * 合并doc * @param path2 主文檔 * @param path3 被合并的文檔 * @param tagName1 在主文檔中要插入的標(biāo)簽 * @param tagName2 被合并文檔的標(biāo)簽 * @param isContain 是否包含被合并文檔標(biāo)簽的上一級標(biāo)簽下的所有結(jié)點 * @return public Document unitXMl(String path2,String path3,String tagName1,String tagName2,boolean isContain){ Document doc1=getDocument(getInputStream(path2)); Document doc2=getDocument(getInputStream(path3)); Element elSub2=getSubElement(doc2,tagName2); Element elSub1=getSubElement(doc1,tagName1); if(isContain){ // doc1.getRootElement().appendContent(elSub2.getParent());//直接插入的根標(biāo)簽下 elSub1.appendContent(elSub2.getParent());//插入到tagName1標(biāo)簽下 }else{ // doc1.getRootElement().appendContent(elSub2); elSub1.appendContent(elSub2); } return doc1; } public static void main(String[] args) { UniteXML ux=new UniteXML(); //將c標(biāo)簽下所有內(nèi)容插入到aa標(biāo)簽下,若參數(shù)設(shè)為true則可將c標(biāo)簽上一級下的所有內(nèi)容插入到aa標(biāo)簽下 Document doc=ux.unitXMl("F:\\test\\a.xml", "F:\\test\\b.xml", "aa", "c", false); ux.writeXML(doc, "F:\\test\\a_test.xml"); } }
//測試用的2個xml如下:
a.xml
方法二:
import java.io. *; //Java基礎(chǔ)包,包含各種IO操作 import java.util. *; //Java基礎(chǔ)包,包含各種標(biāo)準數(shù)據(jù)結(jié)構(gòu)操作 import javax.xml.parsers. *; //XML解析器接口 import org.w3c.dom. *; //XML的DOM實現(xiàn) import javax.xml.transform. *; import javax.xml.transform.dom. *; import javax.xml.transform.stream. *; /** * XML文件合并工具類 * @author GhostFromHeaven */ public class XMLMergeUtil { /** * XML文件的合并處理 * @param mainFileName 待合并處理的xml文件,合并后將更新此文件 * @param subFilename 被合并的xml文件 * @return 合并成功返回true,否則返回false * @throws Exception */ public static boolean isMerging(String mainFileName, String subFilename) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.err.println(pce); // 出現(xiàn)異常時,輸出異常信息 } Document doc_main = null; Document doc_vice = null; // 獲取兩個XML文件的Document try { doc_main = db.parse(mainFileName); doc_vice = db.parse(subFilename); } catch (DOMException dom) { System.err.println(dom.getMessage()); } catch (Exception ioe) { System.err.println(ioe); } // 獲取兩個文件的根節(jié)點 Element root_main = doc_main.getDocumentElement(); Element root_vice = doc_vice.getDocumentElement(); // 下面添加被合并文件根節(jié)點下的每個節(jié)點 NodeList messageItems = root_vice.getChildNodes(); int item_number = messageItems.getLength(); // 如果去掉根節(jié)點下的第一個節(jié)點,那么i從3開始,否則i從1開始 for (int i = 1; i < item_number; i = i + 2) { // 調(diào)用dupliate(),依次復(fù)制被合并XML文檔中根節(jié)點下的節(jié)點 Element messageItem = (Element) messageItems.item(i); dupliate(doc_main, root_main, messageItem); } // 調(diào)用 write To(),將合并得到的Document寫入目標(biāo)XML文檔 boolean isWritten = writeTo(doc_main, mainFileName); 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()){ //節(jié)點相同不用合并 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); // 復(fù)制節(jié)點的屬性 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; } // 復(fù)制子結(jié)點 NodeList sub_messageItems = son.getChildNodes(); int sub_item_number = sub_messageItems.getLength(); if (sub_item_number < 2) { // 如果沒有子節(jié)點,則返回 isdone = true; } else { for (int j = 1; j < sub_item_number; j = j + 2) { // 如果有子節(jié)點,則遞歸調(diào)用本方法 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 DuplicateChildElementObject(); NodeList messageItems = father.getChildNodes(); int item_number = messageItems.getLength(); //首先遍歷所有節(jié)點,查找是否有完全相同的節(jié)點,防止同一節(jié)點已定義多次 for (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)){//同時判斷子節(jié)點是否一致 childElementObject.setNeedDuplicate(false); childElementObject.setElement(messageItem); return childElementObject; } } for (int i = 1; i < item_number; i = i + 2) { Element messageItem = (Element) messageItems.item(i); //判斷節(jié)點是否處于同一級別 if(!messageItem.getNodeName().equals(son.getNodeName())){ continue; } if(isEqualNode(messageItem,son)){//僅判斷當(dāng)前節(jié)點是否一致 if(hasEqualAttributes(messageItem,son)){//當(dāng)前節(jié)點完全相同不需要合并 childElementObject.setNeedDuplicate(false); childElementObject.setElement(messageItem); return childElementObject; }else{//當(dāng)前節(jié)點的屬性不相同,需要合并 childElementObject.setNeedDuplicate(true); childElementObject.setElement(father); return childElementObject; } } } //目標(biāo)文檔該節(jié)點不存在,需要合并到目標(biāo)文檔中 childElementObject.setNeedDuplicate(true); childElementObject.setElement(father); return childElementObject; } /** * 判斷兩個節(jié)點是否相同,未判斷節(jié)點的屬性 * @param arg0 * @param arg * @return */ private static boolean isEqualNode(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; } /** * 判斷節(jié)點的屬性是否相同 * @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:/a.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(); } } } /** * 復(fù)制子節(jié)點對象 * @author Administrator * */ class DuplicateChildElementObject{ private boolean needDuplicate = true;//記錄該節(jié)點是否需要復(fù)制 private Element element = null;//記錄該節(jié)點的父節(jié)點 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; } }
關(guān)于“Android開發(fā)中2個Xml合并的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。