xml文件:在src目录下创建books.xml文件
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
一.读取xml文件
(1)基于光标模型的操作方式
@Test
public void test01() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
// 基于光标模型的操作方式
XMLStreamReader reader = factory.createXMLStreamReader(is);
while (reader.hasNext()) {
int type = reader.next();
// 判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
if (type == XMLStreamConstants.START_ELEMENT) {
System.out.println("<" + reader.getName() + ">");
} else if (type == XMLStreamConstants.CHARACTERS) {
System.out.println(reader.getText().trim());
} else if (type == XMLStreamConstants.END_ELEMENT) {
System.out.println("</" + reader.getName() + ">");
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test02() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while (reader.hasNext()) {
if (reader.next() == XMLStreamConstants.START_ELEMENT) {
String name = reader.getName().toString();
if ("book".equals(name)) {
System.out.println("属性:" + reader.getAttributeName(0) + "=" + reader.getAttributeValue(0));
} else if ("title".equals(name)) {
System.out.print(reader.getElementText() + ":");
} else if ("price".equals(name)) {
System.out.print(reader.getElementText() + "\n");
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行test01()方法,打印结果:
<bookstore>
<book>
<title>
Everyday Italian
</title>
<author>
Giada De Laurentiis
</author>
<year>
2005
</year>
<price>
30.00
</price>
</book>
<book>
<title>
Harry Potter
</title>
<author>
J K. Rowling
</author>
<year>
2005
</year>
<price>
29.99
</price>
</book>
<book>
<title>
XQuery Kick Start
</title>
<author>
James McGovern
</author>
<author>
Per Bothner
</author>
<author>
Kurt Cagle
</author>
<author>
James Linn
</author>
<author>
Vaidyanathan Nagarajan
</author>
<year>
2003
</year>
<price>
49.99
</price>
</book>
<book>
<title>
Learning XML
</title>
<author>
Erik T. Ray
</author>
<year>
2003
</year>
<price>
39.95
</price>
</book>
</bookstore>
运行test02()方法,打印结果:
属性:category=cooking
Everyday Italian:30.00
属性:category=children
Harry Potter:29.99
属性:category=web
XQuery Kick Start:49.99
属性:category=web
Learning XML:39.95
(2)基于迭代模型的操作方式
@Test
public void test03() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
// 基于迭代模型的操作方式
XMLEventReader reader = factory.createXMLEventReader(is);
while (reader.hasNext()) {
// 通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if (event.isStartElement()) {
// 通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if (name.equals("title")) {
System.out.print(reader.getElementText() + ":");
} else if (name.equals("price")) {
System.out.print(reader.getElementText() + "\n");
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印结果:
Everyday Italian:30.00
Harry Potter:29.99
XQuery Kick Start:49.99
Learning XML:39.95
(3)基于过滤器模型的操作方式
@Test
public void test04() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
// 基于过滤器模型的操作方式,可以有效的过滤掉不用进行操作的节点,效率会高一些
XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is), new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
// 返回true表示会显示,返回false表示不显示
if (event.isStartElement()) {
String name = event.asStartElement().getName().toString();
if (name.equals("title") || name.equals("price")) {
return true;
}
}
return false;
}
});
while (reader.hasNext()) {
// 通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if (event.isStartElement()) {
// 通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if (name.equals("title")) {
System.out.print(reader.getElementText() + ":");
} else if (name.equals("price")) {
System.out.print(reader.getElementText() + "\n");
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印结果:
Everyday Italian:30.00
Harry Potter:29.99
XQuery Kick Start:49.99
Learning XML:39.95
(4)基于xpath模型的操作方式
@Test
public void test05() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
// 基于xpath模型的操作方式
// 创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// 通过文档处理对象创建文档对象
Document doc = db.parse(is);
// 创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
// 第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList) xpath.evaluate("//book[@category='web']", doc, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
// 遍历输出相应的结果
Element e = (Element) list.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印结果:
XQuery Kick Start
Learning XML
二.使用XMLStreamWriter创建xml
// 使用XMLStreamWriter创建xml
@Test
public void test06() {
try {
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xsw.writeStartDocument("GB18030", "1.0");
xsw.writeEndDocument();
String ns = "http://stax.test.com/ns";
xsw.writeStartElement("ns", "person", ns);
xsw.writeNamespace("ns",ns);
xsw.writeStartElement(ns, "id");
xsw.writeCharacters("1");
xsw.writeEndElement();
xsw.writeEndElement();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}
打印结果:
<?xml version="1.0" encoding="GB18030"?>
<ns:person xmlns:ns="http://stax.test.com/ns">
<ns:id>1</ns:id>
</ns:person>
三.使用Transformer更新xml文件节点信息
// 使用Transformer更新节点信息
@Test
public void test07() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
// 创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// 通过文档处理对象创建文档对象
Document doc = db.parse(is);
// 创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
// 第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList) xpath.evaluate("//book[title='Learning XML']", doc, XPathConstants.NODESET);
// 获取price节点
Element e = (Element) list.item(0);
e.getElementsByTagName("price").item(0).setTextContent("333.9");
// 通过tranformer修改节点
tf.transform(new DOMSource(doc), new StreamResult(System.out));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>333.9</price>
</book>
</bookstore>