1.jdom解析
SAXBuilder.build("xxx.xml") 解析XML文档
Document.getRootElement() 获取根元素
Element.getChildren() 获取根元素下的子元素,返回List
Element.getAttributeValue(String) 获取指定元素的信息
Element.getChildText 获取指定元素的内容
Element.setAttribute 为元素添加信息
Element.addContent(String,String) 为元素添加子元素内容,也可以直接添加另一个元素节点
Document.setRootElement(Element) 为文档添加根元素
XMLOutputter.output(Document,FileWriter) 将Docuemnt写入到FileWriter文件流中
package com.success;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.List;
/**
* @author zhz
* @describe 解析xml文件
* @date 2019/8/20 20:31
*/
public class XmlParse {
@Test
public void test1() {
SAXBuilder saxBuilder = new SAXBuilder();
Document document = null;
URL resource = XmlParse.class.getClassLoader().getResource("zz.xml");
try {
document = saxBuilder.build(resource);
Element rootElement = document.getRootElement();
List<Element> list = rootElement.getChildren("person");
for (Element element : list) {
System.out.println(element.getAttributeValue("id"));
if (element.getAttributeValue("id").equals("2")) {
Element user = element.getChild("username");
Element password = element.getChild("password");
user.setText("wangwu");
password.setText("123456");
}
}
XMLOutputter outputter = new XMLOutputter();
outputter.output(document, new FileWriter("zz.xml"));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}