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

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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值