JAVA操作XML
XML文件
<template><task id="ddd">aaa</task></template>
构建DOM
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(this.getClass().getResourceAsStream("/template.xml"));//这里指的是src目录下
增加元素
Element element = doc.createElement("task");//创建元素 element.setAttribute("id","AAA");//添加属性 element.appendChild(doc.createTextNode("DDD"));//添加文本节点 doc.getDocumentElement().appendChild(element);//追加到根节点元素中 TransformerFactory tFactory =TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath())); transformer.transform(source, result);//写入到文件
删除元素
doc.getDocumentElement().removeChild(doc.getElementsByTagName("task").item(0));//删除根节点中第一个task元素 TransformerFactory tFactory =TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); MSource source = new DOMSource(doc); StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath())); transformer.transform(source, result);//写入到文件
修改元素
doc.getElementsByTagName("task").item(0).getFirstChild().setNodeValue("ccc");//修改第一个task元素中的内容 TransformerFactory tFactory =TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); OMSource source = new DOMSource(doc);StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath())); transformer.transform(source, result);//写入到文件
查看元素
NodeList tasks = doc.getDocumentElement().getChildNodes(); for(int i = 0;i < tasks.getLength();i++){ System.out.println(((Element)tasks.item(i)).getAttribute("id"));//输出元素的id属性值 System.out.println(tasks.item(i).getNodeValue);//输出元素的内容值 }
相关推荐
Yakamoz 2020-05-26
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
XGQ 2020-07-04
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16
wcqwcq 2020-06-14
yuanye0 2020-06-14
zhongliwen 2020-06-13