java中对xml进行解析、创建、更新、删除的示例

来源:互联网 发布:c语言中最小公倍数 编辑:程序博客网 时间:2024/06/07 20:27
package com.inspur.common.utils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.StringReader;import java.util.ArrayList;import java.util.List;import java.util.Map;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.CDATASection;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.xml.sax.SAXException;public class XmlParseUtil {/*public static void main(String args[]) {String text = "<?xml version=\"1.0\"?><multimedia><pictures><picture name=\"P201607221301370650.jpg\"><desc><![CDATA[]]></desc></picture><picture name=\"P201607221301548970.jpg\"><desc><![CDATA[]]></desc></picture><picture name=\"P201607221302266440.jpg\"><desc><![CDATA[]]></desc></picture></pictures><audios/><videos/><offices/></multimedia>";long begin = System.currentTimeMillis();parse(text);long after = System.currentTimeMillis();System.out.println("DOM用时" + (after - begin) + "毫秒");}*///解析public static String parse(String protocolXML) {String picimages = "";try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document doc = builder.parse(new InputSource(new StringReader(protocolXML)));NodeList books = doc.getElementsByTagName("picture");if (books != null) {for (int i = 0; i < books.getLength(); i++) {Element book = (Element) books.item(i);String picname = book.getAttribute("name");picimages += picname+",";}}} catch (Exception e) {e.printStackTrace();}return picimages;}//创建xml格式字符串public static String createXML(List<Map<String,Object>> fileList) throws ParserConfigurationException, TransformerException {String xmlStr = null;        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        DocumentBuilder builder = factory.newDocumentBuilder();        Document document = builder.newDocument();        document.setXmlVersion("1.0");                Element multimedia = document.createElement("multimedia");                        Element pictures = document.createElement("pictures");                for(int i =0; i<fileList.size();i++){            Element picture = document.createElement("picture");            picture.setAttribute("name", (String)fileList.get(i).get("fjmc"));                        Element desc = document.createElement("desc");            CDATASection cdata = document.createCDATASection("");            desc.appendChild(cdata);                        pictures.appendChild(picture);            pictures.appendChild(desc);        }                Element audios = document.createElement("audios");        Element videos = document.createElement("videos");        Element offices = document.createElement("offices");                multimedia.appendChild(pictures);        multimedia.appendChild(audios);        multimedia.appendChild(videos);        multimedia.appendChild(offices);                document.appendChild(multimedia);                TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer transFormer = transFactory.newTransformer();        DOMSource domSource = new DOMSource(document);                //export string        ByteArrayOutputStream bos = new ByteArrayOutputStream();        transFormer.transform(domSource, new StreamResult(bos));        xmlStr = bos.toString();                        //-------            //save as file/*            File file = new File("TelePhone.xml");            if(!file.exists()){                file.createNewFile();            }            FileOutputStream out = new FileOutputStream(file);            StreamResult xmlResult = new StreamResult(out);            transFormer.transform(domSource, xmlResult);*/            //--------                return xmlStr;}//更新public static String updateXML(String protocolXML,List<Map<String,Object>> fileList) throws ParserConfigurationException, SAXException, IOException, TransformerException {String xmlStr = "";DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document document = builder.parse(new InputSource(new StringReader(protocolXML)));Element pictures=(Element) document.getElementsByTagName("pictures").item(0);//这里是获得pictures标签        for(int i =0; i<fileList.size();i++){            Element picture = document.createElement("picture");            picture.setAttribute("name", (String)fileList.get(i).get("fjmc"));                        Element desc = document.createElement("desc");            CDATASection cdata = document.createCDATASection("");            desc.appendChild(cdata);                        pictures.appendChild(picture);            pictures.appendChild(desc);        }                TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer transFormer = transFactory.newTransformer();        DOMSource domSource = new DOMSource(document);                //export string        ByteArrayOutputStream bos = new ByteArrayOutputStream();        transFormer.transform(domSource, new StreamResult(bos));        xmlStr = bos.toString();return xmlStr;}//删除节点public static String deleteChildXML(String protocolXML,String[] deleteList) throws ParserConfigurationException, SAXException, IOException, TransformerException {String xmlStr = "";DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document document = builder.parse(new InputSource(new StringReader(protocolXML)));NodeList picturenode = document.getElementsByTagName("picture");List<Element> deleteNode = new ArrayList<Element>();for( int i=0;i<picturenode.getLength();i++){Element tmp = (Element)picturenode.item(i);for(int j=0;j<deleteList.length;j++){if(tmp.getAttribute("name").equals(deleteList[j])){deleteNode.add(tmp);break;}}}for(Element tmpe :deleteNode){tmpe.getParentNode().removeChild(tmpe);}        TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer transFormer = transFactory.newTransformer();        DOMSource domSource = new DOMSource(document);                //export string        ByteArrayOutputStream bos = new ByteArrayOutputStream();        transFormer.transform(domSource, new StreamResult(bos));        xmlStr = bos.toString();return xmlStr;}}

0 0
原创粉丝点击