欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java使用DOM和DOM4J分别解析XML文件步骤以及代码

程序员文章站 2022-05-29 11:34:19
...

XML文件如下:
PhoneType.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<PhoneInfo>
	
	<Brand name="苹果">
		<Type name="iPhone 6s"/>
		<Type name="iPhone 8"/>
		<Type name="iPhone X"/>
		<Type name="iPhone 11 Pro"/>
	</Brand>
	<Brand name="三星">
        <Type name="Note 10"/>
    </Brand>
</PhoneInfo>

newInfo.xml

<?xml version="1.0" encoding="UTF-8"?>

<PhoneInfo> 
  <Brand name="苹果" id="1"> 
    <Type name="iPhone 6s"/>  
    <Type name="iPhone 8"/>  
    <Type name="iPhone X"/>  
    <Type name="iPhone 11 Pro"/> 
  </Brand>  
  <Brand name="华为" id="3">
    <Type name="Mate 10 Pro"/>
  </Brand>
</PhoneInfo>

DOM解析XML文件

package com.biubiubiu.demo01XML.DOM;
/**
 * 使用DOM解析XML文件
 * @author 11142
 *
 */

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseXMLDemoDOM {
	//PhoneType.xml对应的Document对象
	private Document document;
	
	//获得DOM树(Document对象)
	public void getDom() {
		//获得解析器工厂(创建解析器工厂对象)
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			//根据解析器工厂对象获得解析器(创建解析器对象)
			DocumentBuilder builder = factory.newDocumentBuilder();
			//解析器来解析XML文件获得Document对象
			document = builder.parse("PhoneType.xml");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取手机品牌及型号相关信息
	public void showInfo() {
		//以Document做起点,先拿到所有的Brand节点
		NodeList brands = document.getElementsByTagName("Brand");
		//遍历brands,从中拿出每一个Brand
		for(int i=0; i<brands.getLength(); i++) {
			Node node = brands.item(i);
			Element eleBrand = (Element)node;
			String brandName = eleBrand.getAttribute("name");
			System.out.println(brandName);
			//继续查找,找每个Brand的子节点出来
			NodeList types = eleBrand.getChildNodes();
			for(int j=0; j<types.getLength(); j++) {
				Node typeNode = types.item(j);
				//判断是元素节点才要
				if(typeNode.getNodeType() == Node.ELEMENT_NODE) {
					Element typeEle = (Element)typeNode;
					System.out.println("\t" + typeEle.getAttribute("name"));
				}
			}
		}
	}
	
	//为XML文件添加元素
	public void addEle() {
		//(1)创建Brand,<Brand name="三星">
		Element brand = document.createElement("Brand");
		brand.setAttribute("name", "三星");
		//<Type name="Note 10">
		Element type = document.createElement("Type");
		type.setAttribute("name", "Note 10");
		//将Type作为Brand的子元素
		brand.appendChild(type);
		//将Brand放到PhoneInfo中去
		document.getElementsByTagName("PhoneInfo").item(0).appendChild(brand);
		saveXML("PhoneType.xml");
	}
	
	//添加后,保存xml文件(需要借助转换器:源(最新的DOM树) ---> 目的地(PhoneType.xml),借助输出流)
	public void saveXML(String path) {
		//转换器工厂
		TransformerFactory factory = TransformerFactory.newInstance();
		factory.setAttribute("indent-number", 4);
		try {
			//转换器
			Transformer transformer = factory.newTransformer();
			//指定转换格式
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "YES");
			
			//源(最新的DOM树) ---> 目的地(PhoneType.xml)
			DOMSource source = new DOMSource(document);
			
			OutputStream out = new FileOutputStream(path);
			StreamResult result = new StreamResult(new OutputStreamWriter(out, "UTF-8"));
			
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
	
	//修改元素
	public void updateEle() {
		//获取所有的Brand
		NodeList brands = document.getElementsByTagName("Brand");
		for(int i=0; i<brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element brandEle = (Element)brand;
			//添加ID序号
			brandEle.setAttribute("id", i+"");
		}
		saveXML("PhoneType.xml");
	}
	
	//删除元素
	public void deleteEle() {
		//获取所有的Brand
		NodeList brands = document.getElementsByTagName("Brand");
		for(int i=0; i<brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element brandEle = (Element)brand;
			//删除华为
			if(brandEle.getAttribute("name").equals("华为")) {
				brandEle.getParentNode().removeChild(brand);
			}
		}
		saveXML("PhoneType.xml");
	}
	
	public static void main(String[] args) {
		ParseXMLDemoDOM pxd = new ParseXMLDemoDOM();
		pxd.getDom();
//		pxd.addEle();
//		pxd.updateEle();
		pxd.deleteEle();
		pxd.showInfo();
	}
	
}

DOM4J解析XML文件
需要引入dom4j.jar,百度下载即可

package com.biubiubiu.demo01XML.DOM4J;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
 * 使用DOM4J解析XML文件
 * @author 11142
 *
 */
public class ParseXMLDemoDOM4J {
	private Document document;
	
	//获得document对象
	public void loadDocument() {
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(new File("PhoneType.xml"));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	//显示手机的品牌和型号
	public void showInfo() {
		//获取xml根节点
		Element root = document.getRootElement();
		//获取所有<Brand>
		Iterator eleBrands = root.elementIterator();
		while(eleBrands.hasNext()) {
			Element brand = (Element)eleBrands.next();
			System.out.println(brand.attributeValue("name"));
			Iterator eleTypes = brand.elementIterator();
			while(eleTypes.hasNext()) {
				Element type = (Element)eleTypes.next();
				System.out.println("\t" + type.attributeValue("name"));
			}
		}
	}
	
	//增加手机品牌信息
	public void addNewPhone() {
		//获得xml根元素
		Element root = document.getRootElement();
		//创建<Brand name="华为">
		Element eleBrand  = root.addElement("Brand");
		eleBrand.addAttribute("name", "华为");
		//创建<Type name="Mate 10 Pro">
		Element eleType = eleBrand.addElement("Type");
		eleType.addAttribute("name", "Mate 10 Pro");
		saveXml("newInfo.xml");
	}
	
	//修改节点增加ID属性
	public void updatePhone() {
		Element root = document.getRootElement();
		Iterator eleBrands = root.elementIterator();
		int id = 0;
		while (eleBrands.hasNext()) {
			Element brand = (Element)eleBrands.next();
			id++;
			brand.addAttribute("id", id+"");
		}
		saveXml("newInfo.xml");
	}
	
	//删除节点:三星
	public void deletePhone() {
		Element root = document.getRootElement();
		Iterator eleBrands = root.elementIterator();
		while (eleBrands.hasNext()) {
			Element brand = (Element)eleBrands.next();
			if(brand.attributeValue("name").equals("三星")) {
				brand.getParent().remove(brand);
			}
		}
		saveXml("newInfo.xml");
	}
	
	//保存修改后的xml文件
	public void saveXml(String path) {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = null;
//		format.setEncoding("GBK");//可以设置编码
		try {
			writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path)),format);
			writer.write(document);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}try {
			
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		ParseXMLDemoDOM4J pxDom4j = new ParseXMLDemoDOM4J();
		pxDom4j.loadDocument();
		pxDom4j.addNewPhone();
		pxDom4j.updatePhone();
		pxDom4j.deletePhone();
		pxDom4j.showInfo();
	}
	
}