Java对于Xml文件的读取有多种方式
Xml文件的介绍
XML 是可扩展标记语言(Extensible Markup Language)的缩写,其中的 标记(markup)是关键部分。
- XML文档的内容和结构完全分离
- 互操作性强(在不同操作系统上的不同系统之间通信)
- 规范统一(具有统一的格式和语法)
- 支持多种编码(XML文档本身包含了所使用编码的记录,这方便了多语言系统对数据的处理)
- 可扩展性
使用场合也多是数据交换、Web服务、内容管理、Web集成、配制等方面。
Java读取方式
文件目录
<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="001">
<title>think in java</title>
<language>Java</language>
<author>JK.Rowling</author>
</book>
<book id="002">
<title>Learning xml</title>
<language>xml</language>
<author>Erik T. Ray</author>
</book>
<book id="003">
<title>Spring</title>
<language>Java</language>
<author>Aaron Diao</author>
</book>
</books>
1.直接使用javax.xml中的方法
package com.myloverqian.readxml;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
/**
* Created by dzw on 2015/12/23.
*/
public class ReadDomXml {
/** 文件路径 */
private static String path = "xmlSample/src/main/resources/dom.xml";
/** 读取root节点 */
private static Element ReadXml() {
Element root = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(path));
root = document.getDocumentElement();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return root;
}
/** 打印节点名称和属性 */
public static void main(String[] args) {
Element root = ReadXml();
System.out.println("books:" + root.getAttribute("books"));
NodeList list = root.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
Element bookName = (Element) list.item(i);
System.out.println("\t" + "book=" + bookName.getAttribute("id"));
NodeList childNodes = bookName.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node item = childNodes.item(j);
if (item instanceof Element) {
System.out.println("\t\t" + item.getNodeName() + "=" + item.getTextContent());
}
}
}
}
}
之后的内容会逐渐写出来,这是我自己写的东西,时间比较紧,如有疏漏,还望指正。