本文系摘抄再整理,來自http://www.w3school.com.cn/xml/xml_attributes.asp等
一、XML解析技術有兩種
根據XML的層級結構在內存中分配一個樹形結構,把XML的標籤,屬性和文本等元素都封裝成樹的節點對象
- 優點: 便於實現增 刪 改 查
- 缺點: XML文件過大可能造成內存溢出
採用事件驅動模型邊讀邊解析:從上到下一行行解析,解析到某一元素, 調用相應解析方法
- 優點: 不會造成內存溢出,
- 缺點: 查詢不方便,但不能實現 增 刪 改
不同的公司和組織提供了針對DOM和SAX兩種方式的解析器
- SUN的jaxp
- Dom4j組織的dom4j(最常用:如Spring)
- JDom組織的jdom
關於這三種解析器淵源可以百度下:java解析xml文件四種方式.
二、JAXP 解析 Javax.xml.parsers
JAXP是JavaSE的一部分,在javax.xml.parsers包下,分別針對dom與sax提供瞭如下解析器:
- DocumentBuilder
- DocumentBuilderFactory
- SAXParser
- SAXParserFactory
三、XML格結構
XML 文檔形成了一種樹結構,它從“根部”開始,然後擴展到“枝葉”
1、一個 XML 文檔實例
XML 使用簡單的具有自我描述性的語法:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
第一行是 XML 聲明。它定義 XML 的版本 (1.0) 和所使用的編碼 (ISO-8859-1 = Latin-1/西歐字符集)。
下一行描述文檔的根元素(像在說:“本文檔是一個便籤”):
<note>
接下來 4 行描述根的 4 個子元素(to, from, heading 以及 body):
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
最後一行定義根元素的結尾:
</note>
從本例可以設想,該 XML 文檔包含了 John 給 George 的一張便籤。
2、XML 文檔形成一種樹結構——DOM節點樹
XML DOM 把 XML 文檔視爲一種樹結構。這種樹結構被稱爲節點樹。
可通過這棵樹訪問所有節點。可以修改或刪除它們的內容,也可以創建新的元素。
這顆節點樹展示了節點的集合,以及它們之間的聯繫。這棵樹從根節點開始,然後在樹的最低層級向文本節點長出枝條。
XML 文檔必須包含根節點(根元素)。該元素是所有其他元素的父元素。
XML 文檔中的元素形成了一棵文檔樹。這棵樹從根部開始,並擴展到樹的最底端。
所有元素均可擁有子元素:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
父、子以及同胞等術語用於描述元素之間的關係。父元素擁有子元素。相同層級上的子元素成爲同胞(兄弟或姐妹)。
所有元素均可擁有文本內容和屬性(類似 HTML 中)。
實例
上圖表示下面的 XML 中的一本書:
<bookstore>
<book category="COOKING" group="test01">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN" group="test01">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB" group="test01">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
例子中的根元素是 <bookstore>。文檔中的所有 <book> 元素都被包含在 <bookstore> 中。
<book> 元素有 4 個子元素:<title>、< author>、<year>、<price>。
3、元素節點、屬性節點、 文本節點、 文檔節點區別
如果從一個xml文檔來看,不太好區分什麼這幾個節點,這幾個節點是從 " XML DOM 把 XML 文檔視爲一種樹結構--節點樹 " 來說的,只有轉化爲節點樹,纔有這幾個節點的概念。
<bookstore>
<book category="COOKING" group="test01">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN" group="test01">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB" group="test01">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
(1)元素節點:一般是擁有一對開閉合標籤的元素整體,例如下圖中的<ul>...</ul>這一部分都屬於一個元素節點。
(2)屬性節點:一般是元素節點的屬性,比如下圖中的“寬度”屬性 也就是width="80 px"這一部分。
(3)文本節點:DOM中用於呈現文本的部分,如下圖中的 “點我” 兒子,一般被包含在元素節點的開閉合標籤內部。
節點信息
每個節點都擁有包含着關於節點某些信息的屬性。這些屬性是:
nodeName(節點名稱)
nodeValue(節點值)
nodeType(節點類型)
4、節點與元素的區別:
Element是Node的擴展,除了Element之外,Attribute(屬性)、Text(文本節點)、PI(處理指令)、 Document(文檔)等等都是Node。
例如,用Element可以方便的獲得Node的屬性getAttribute(String attrName)
如果用Node,可以得到一個屬性集,還要進一步檢索纔可得到想要的屬性。
四、實例DEMO
1、xml文件:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myTestBean" class="com.wqc.bean.MyTestBean"/>
</beans>
2、TestParseDemo.java(打印出xml的內容,循環解析)
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.SAXException;
public class TestParseDemo {
public static void main(String[] args) {
//File docFile = new File("src/main/resources/orders.xml");
File docFile = new File("src/main/resources/applicationContext.xml");
Document doc = null;
Element root = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);//名稱空間支持,沒有這個getNamespaceURI將會是null
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(docFile);
root = doc.getDocumentElement();
//System.out.println(root.getNamespaceURI());
int count = 0;
parse(root, count);
} catch (ParserConfigurationException pex) {
System.out.println("解析配置錯誤:" + pex.getMessage());
} catch (SAXException saex) {
System.out.println("sax錯誤:" + saex.getMessage());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
static void parse(Element element, int count)
{
//System.out.println(count++);
String nodeName = element.getNodeName();
System.out.print("<" + nodeName);
parseAttr(element);
System.out.print(">");
NodeList nodeList = element.getChildNodes();
if (nodeList != null)
{
int length = nodeList.getLength();
for (int i = 0; i < length; i++)
{
Node node = nodeList.item(i);
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE)
{
//System.out.println("ELEMENT_NODE--uri:"+element.getNamespaceURI());
//遞歸
parse((Element) node, count);
}
else if (nodeType == Node.TEXT_NODE)
{
//這裏會讀出\n\t,所以打印不用換行
System.out.print("TEXT_NODE:"+node.getNodeValue());
}
else if (nodeType == Node.COMMENT_NODE)
{
System.out.print("<!--" + node.getNodeValue() + "-->");
}
else if (nodeType == Node.ATTRIBUTE_NODE)
{
System.out.println("ATTRIBUTE_NODE--uri:"+element.getNamespaceURI());
}
}
}
System.out.print("</" + nodeName + ">");
}
static void parseAttr(Element element)
{
NamedNodeMap attrMap = element.getAttributes();
if (attrMap != null && attrMap.getLength() > 0)
{
System.out.print(" ");
int length = attrMap.getLength();
for (int i = 0; i < length; i++)
{
Node attr = attrMap.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
if (i > 0)
{
System.out.print(" ");
}
System.out.print(attrName + "=\"" + attrValue + "\"");
}
}
}
}
輸出結果:
3、DomNSTest.java 打印出NamespaceURL
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public class DomNSTest {
public static void printNSInfo(Node node){
//System.out.println("Namespace Uri:"+node.getNamespaceURI());
short type=node.getNodeType();
switch(type){
case Node.ELEMENT_NODE:
if(node.getNamespaceURI()!=null){
System.out.println("Element Name:"+node.getNodeName());
System.out.println("Local Name:"+node.getLocalName());
System.out.println("Namespace Prefix:"+node.getPrefix());
System.out.println("Namespace Uri:"+node.getNamespaceURI());
System.out.println("---------------");
}
if(node.hasAttributes()){
NamedNodeMap map=node.getAttributes();
int len=map.getLength();
for (int i = 0; i < len; i++) {
Node attr=map.item(i);
if(attr.getNamespaceURI()!=null){
printNSInfo(attr);
}
}
}
Node child=node.getFirstChild();
System.out.println(child);
while(child!=null)
{
printNSInfo(child);
child=child.getNextSibling();
}
break;
case Node.ATTRIBUTE_NODE:
System.out.println("Attribute Name:"+node.getNodeName());
System.out.println("Local Name:"+node.getLocalName());
System.out.println("Namespace Prefix:"+node.getPrefix());
System.out.println("Namespace Uri:"+node.getNamespaceURI());
System.out.println("---------------");
break;
default:
break;
}
}
public static void main(String[] args) {
File docFile = new File("src/main/resources/applicationContext.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);//名稱空間支持
try {
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse(docFile);
printNSInfo(doc.getDocumentElement());
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸出結果: