Java : DOM解析xml 文件/ 字符串
Posted Mars-xq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java : DOM解析xml 文件/ 字符串相关的知识,希望对你有一定的参考价值。
参考:
一、xml源文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sex="man">小明</name>
<nickName>明明</nickName>
</student>
<student>
<name sex="woman">小红</name>
<nickName>红红</nickName>
</student>
<student>
<name sex="man">小亮</name>
<nickName>亮亮</nickName>
</student>
</students>
二、实体类
package day210624;
public class Student {
private String name;
private String sex;
private String nickName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\\'' +
", sex='" + sex + '\\'' +
", nickName='" + nickName + '\\'' +
'}';
}
}
三、解析工具
package day210624;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class Parser {
public static Document getDocumentFromString(String xml)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xml));
return builder.parse(inputSource);
}
public static Document getDocumentFromFile(File file)
throws ParserConfigurationException, SAXException, IOException {
//一系列的初始化
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//获得Document对象
return builder.parse(file);
}
public static List<Student> parse(Document document) {
/*============获得Document对象即可解析xml======================*/
List<Student> list = new ArrayList<>();
//获得student的List
NodeList studentList = document.getElementsByTagName("student");
//遍历student标签
for (int i = 0; i < studentList.getLength(); i++) {
//获得student标签
Node node_student = studentList.item(i);
//获得student标签里面的标签
NodeList childNodes = node_student.getChildNodes();
//新建student对象
Student student = new Student();
//遍历student标签里面的标签
for (int j = 0; j < childNodes.getLength(); j++) {
//获得name和nickName标签
Node childNode = childNodes.item(j);
//判断是name还是nickName
if ("name".equals(childNode.getNodeName())) {
String name = childNode.getTextContent();
student.setName(name);
//获取name的属性
NamedNodeMap nnm = childNode.getAttributes();
//获取sex属性,由于只有一个属性,所以取0
Node n = nnm.item(0);
student.setSex(n.getTextContent());
} else if ("nickName".equals(childNode.getNodeName())) {
String nickName = childNode.getTextContent();
student.setNickName(nickName);
}
}
//加到List中
list.add(student);
}
return list;
}
/*
* 添加元素到XML中
*/
public static void createElement(Document doc) {
Element root = doc.getDocumentElement();
// 通过Document对象的getDocumentElement()方法得到根节点
Element newStudent = doc.createElement("student");
// 通过Document对象的createElement(String tagName)方法得到新的元素
Element newName = doc.createElement("name");
// 通过Document对象的createElement(String tagName)方法得到新的元素
newName.setTextContent("xq");
// 通过调用Element对象的setTextContent(String textContent)方法为赋值
newName.setAttribute("sex", "man");
// 通过调用Element对象的setAttribute(String name,String value)方法为id赋值
newStudent.appendChild(newName);
Element newNickName = doc.createElement("nickName");
// 通过Document对象的createElement(String tagName)方法得到新的元素
newNickName.setTextContent("able");
// 通过调用Element对象的setTextContent(String textContent)方法为赋值
newStudent.appendChild(newNickName);
root.appendChild(newStudent);
// 添加到根节点中
}
}
四、测试解析:
package day210624;
import org.w3c.dom.Document;
import java.io.File;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
try {
//解析xml文件
File file = new File("/Users/tmk/IdeaProjects/JavaDemo/src/day210624/student.xml");
Document documentFromFile = Parser.getDocumentFromFile(file);
List<Student> students = Parser.parse(documentFromFile);
System.out.println("students = " + students);
//解析xml字符串
String xml =
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"no\\"?>" +
"<students>" +
"<student>" +
"<name sex=\\"man\\">小明</name>" +
"<nickName>明明</nickName>" +
"</student>" +
"<student>" +
"<name sex=\\"woman\\">小红</name>" +
"<nickName>红红</nickName>" +
"</student>" +
"<student>" +
"<name sex=\\"man\\">小亮</name>" +
"<nickName>亮亮</nickName>" +
"</student>" +
"</students>";
Document documentFromString = Parser.getDocumentFromString(xml);
Parser.createElement(documentFromString);//添加一个节点
List<Student> list = Parser.parse(documentFromString);
System.out.println("list = " + list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//students =
// [Student{name='小明', sex='man', nickName='明明'},
// Student{name='小红', sex='woman', nickName='红红'},
// Student{name='小亮', sex='man', nickName='亮亮'}]
//list =
// [Student{name='小明', sex='man', nickName='明明'},
// Student{name='小红', sex='woman', nickName='红红'},
// Student{name='小亮', sex='man', nickName='亮亮'},
// Student{name='xq', sex='man', nickName='able'}]
以上是关于Java : DOM解析xml 文件/ 字符串的主要内容,如果未能解决你的问题,请参考以下文章