解析XML文件并且进行增删改查操作

phoneinfo.xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<phoneinfo>
	<brand id="0" name="小米">
		<type name="MI5"/>
		<type name="NOTE"/>
		<type name="MI5S"/>
	</brand>
	<brand id="1" name="华为">
		<type name="M1"/>
		<type name="荣耀8"/>
		<type name="荣耀8puls"/>
	</brand>
	<brand id="2" name="苹果">
        <type name="iphone7"/>
        <type name="iphone6"/>
    </brand>
</phoneinfo>


解析XML文件,并且增删改查操作:

package com.hfxt;

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;
//解析XMl文件(并增、删、改、查、操作)
public class DomXml {
	private Document document;
	
	public static void main(String[] args){
		DomXml dx = new DomXml();
		dx.getDom();
		//dx.addEle();
		dx.deleteEle();
		dx.updateEle();
		dx.showInfo();
	}

	//获取DOM树
	public void getDom(){
		try {
			//获取XML解析器
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			//创建解析器工场
			DocumentBuilder builder = factory.newDocumentBuilder();
			//解析xml文件
			document = builder.parse("phoneinfo.xml");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//添加手机信息
	public void addEle(){
		//添加节点
		Element brand = document.createElement("brand");
		//添加属性并且赋值
		brand.setAttribute("name","苹果");
		//添加子节点
		Element type = document.createElement("type");
		Element type1 = document.createElement("type");
		//添加属性并且赋值
		type.setAttribute("name","iphone7");
		type1.setAttribute("name","iphone6");
		//将type作为brand的子节点
		brand.appendChild(type);
		brand.appendChild(type1);
		//将phoneinfo作为头标签元素
		document.getElementsByTagName("phoneinfo").item(0).appendChild(brand);
		saveEle("phoneinfo.xml");
	}

	//保存信息到XML文件中(用转换器、输出流)
	public void saveEle(String path){
		//创建转换器工厂
		TransformerFactory factory = TransformerFactory.newInstance();
		//指定格式(格式缩进)
		factory.setAttribute("indent-number",4);
		try {
			//获取转换器
			Transformer transFormer = factory.newTransformer();
			//是否缩进格式
			transFormer.setOutputProperty(OutputKeys.INDENT,"Yes");
			//将DOM文件写入source里
			DOMSource source = new DOMSource(document);
			//指定路径
			OutputStream os = new FileOutputStream(path);
			StreamResult result = new StreamResult(new OutputStreamWriter(os,"UTF-8"));
			
			//将文件输入到指定位置
			transFormer.transform(source,result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//删除信息
	public void deleteEle(){
		//获取节点集合
		NodeList brand = document.getElementsByTagName("brand");
		//遍历集合
		for(int i=0;i<brand.getLength();i++){
			Node brandNode = brand.item(i);
			Element eleBrand = (Element)brandNode;
			if(eleBrand.getAttribute("name").equals("苹果")){
				eleBrand.getParentNode().removeChild(eleBrand);
			}
		}
		saveEle("phoneinfo.xml");
	}
	
	//修改XML文件信息
	public void updateEle(){
		//获取节点的集合
		NodeList brand = document.getElementsByTagName("brand");
		//遍历节点集合
		for(int i=0;i<brand.getLength();i++){
			Node brandNode =brand.item(i);
			//将节点转换成元素
			Element eleBrand = (Element)brandNode;
			//增加ID的属性
			eleBrand.setAttribute("id",i+"");
		}
		//保存信息
		saveEle("phoneinfo.xml");
	}
	
	//获取手机信息
	public void showInfo(){
		//获取节点的集合
		NodeList brand = document.getElementsByTagName("brand");
		//遍历节点的集合获取每一个节点
		for(int i=0;i<brand.getLength();i++){
			Node nodeBrand = brand.item(i);
			//将节点转换成元素
			Element eleBrand = (Element)nodeBrand;
			//通过name属性获取对应的值
			System.out.println(eleBrand.getAttribute("name"));
			
			//获取子节点集合
			NodeList type = nodeBrand.getChildNodes();
			//遍历子节点结合
			for(int j=0;j<type.getLength();j++){
				Node nodeType = type.item(j);
				//判断是否为节点
				if(nodeType.getNodeType() == Node.ELEMENT_NODE){
					Element eleType = (Element)nodeType;
					System.out.println("\t"+eleType.getAttribute("name"));
				}
			}
		}
	}
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值