xml解析
在java应用开发中我们和xml打交道得机会太平凡了,一般情况下我看会用JDOM或是DOM4j来解析我们得XML文件,下面是一个Dom4j解析xml文件得例子,其中包括了对xml文件得取值、赋值、提取节点、节点得遍历等。
SAXReader reader =
new
SAXReader();
Document doc = reader.read(...);
List childNodes = doc.selectNodes("//Config/Child/ChildNode"
);
for
(Object obj:childNodes) {
Node childNode = (Node)obj;
String name = childNode.valueOf("@name"
);
String text = childNode.getText();
}
一.Document对象相关
1
.读取XML文件,获得document对象.
SAXReader reader = new
SAXReader();
Document document = reader.read(new
File(
"input.xml"
));
2
.解析XML形式的文本,得到document对象.
String text = "<members></members>"
;
Document document = DocumentHelper.parseText(text);
3
.主动创建document对象.
Document document = DocumentHelper.createDocument();
Element root = document.addElement("members"
);
// 创建根节点
二.节点相关
1
.获取文档的根节点.
Element rootElm = document.getRootElement();
2
.取得某节点的单个子节点.
相关文档:
HTML.html文件
<div align="center" class="style1">
<p>冰棍列表</p>
<p></p>
<table width="400" border="1">
<tr>
<th scope="col"><font size="4">品牌</font></th> ......
wsdl.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<definitions name="MobilePhoneService"
targetNamespace="www.mobilephoneservice.com/MobilePhoneService-interface"
xmlns="http://schemas.xmlsoap.org/wsdl/"
  ......
test.html
———————————————————————————————————————& ......
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<mobile-list>
<mobile type="Nokia2652">
<wap2>false</wap2>
<width>115</width>
</mobile>
<mobile type="Nokia2650">
......
<?
/**
* xml2array() will convert the given XML text to an array in the XML structure.
* Link: http://www.bin-co.com/php/scripts/xml2array/
* Arguments : $contents - The XML text
* $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the ......