dom4j学习总结(一)
(一)创建Document的基本操作
/**
* XML基本操作
*/
public void BaseOperation(){
//创建一个document
Document document=DocumentHelper.createDocument();
//创建根结点
Element root=document.addElement("root");
//为根结点添加一个book节点
Element book1=root.addElement("book");
//为book1添加属性type
book1.addAttribute("type","science");
//为book1添加name子节点
Element name1=book1.addElement("Name");
//并设置其name为"Java"
name1.setText("Java");
//为book1创建一个price节点,并设其价格为100
book1.addElement("price").setText("100");
//为根结点添加第二个book节点,并设置该book节点的type属性
Element book2=root.addElement("book").addAttribute("type","science");
//为book1添加name子节点
Element name2=book2.addElement("Name");
//并设置其name为"Oracle"
name2.setText("Oracle");
//为book1创建一个price节点,并设其价格为200
book2.addElement("price").setText("200");
//输出xml
System.out.println(document.asXML());
}
调用BaseOperation,输出结果为:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<book type="science">
<Name>Java</Name>
<price>100</price>
</book>
<book type="science">
<Name>Oracle</Name>
<price>200</price>
</book>
</root>
(二)根据一个符合Document格式的字符串来生成一个Document
/**将字符串转化为Document
* @param str 输入的字符串
* @return 生成的document
* @throws DocumentException
*/
public Document parserStrtoDocument(String str) throws DocumentException{
Document document=DocumentHelper.parseText(str);
return document;
}
调用示例:
String str="<root><book type='science'><Name>Java</Name><price>100</price></book></root>";
Document document = parserStrtoDocument(str);
System.out.println(document.asXML());
输出结果为:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<book type="science">
<Name>Java</Name>
<price>100</price>
</book>
</root>
(三)取得xml节点属性的基本方法
/**
* 取得xml的节点和属性的值
* @throws DocumentException
*/
public void getBaseInfofromDocument() throws DocumentException{
String str="<root><book type='science'><Name>Java</Name><price>100</price></book></root>";
//生成一个Document
Document document = DocumentHelper.parseText(str);
//取得根结点
Element root=document.getRootElement();
//取得book节点
Element book=root.element("book");
//取得book节点的type属性的值
String type=book.attributeValue("type");
//取得Name节点
Element name=book.element("Name");
//取得书名
String bookname=name.getText();
//取得书的价钱
int price=Integer.parseInt(book.element("price").getText());
//输出书目信息
System.out.println("书名:" bookname);
System.out.println("所属类别:" type);
System.out.println("价格:" price);
}
调用getBaseInfofromDocument,输出结果为:
书名:Java
所属类别:science
价格:100
(四)利用迭代,xpath取得节点及其属性值
/**利用迭代,xpath取得xml的节点及其属性值
* @throws DocumentException
*/
public void getComplexInfofromDocument() throws DocumentException{
String str="<root><book type='science'><Name>Java</Name><price>100</price></book>"
"<book type='science'><Name>Oracle</Name><price>120</price></book>"
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!


