使用 dom4j 解析 XML
http://www.ibm.com/developerworks/cn/xml/x-dom4j.html
创建文档
本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。
使用 import 语句导入 dom4j API 类:
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element;
使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.*;
public class XmlDom4J{
public void generateDocument(){
Document document = DocumentHelper.createDocument();
Element catalogElement = document.addElement("catalog");
catalogElement.addComment("An XML Catalog");
catalogElement.addProcessingInstruction("target","text");
Element journalElement = catalogElement.addElement("journal");
journalElement.addAttribute("title", "XML Zone");
journalElement.addAttribute("publisher", "IBM developerWorks");
Element articleElement=journalElement.addElement("article");
articleElement.addAttribute("level", "Intermediate");
articleElement.addAttribute("date", "December-2001");
Element titleElement=articleElement.addElement("title");
titleElement.setText("Java configuration with XML Schema");
Element authorElement=articleElement.addElement("author");
Element firstNameElement=authorElement.addElement("firstname");
firstNameElement.setText("Marcello");
Element lastNameElement=authorElement.addElement("lastname");
lastNameElement.setText("Vitaletti");
document.addDocType("catalog",
null,"file://c:/Dtds/catalog.dtd");
try{
XMLWriter output = new XMLWriter(
new FileWriter( new File("c:/catalog/catalog.xml") ));
output.write( document );
output.close();
}
catch(IOException e){System.out.println(e.getMessage());}
}
public static void main(String[] argv){
XmlDom4J dom4j=new XmlDom4J();
dom4j.generateDocument();
}} 这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。
![]() ![]() |
修改文档
这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。
使用 SAXReader 解析 XML 文档 catalog.xml:
SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); |
SAXReader 包含在 org.dom4j.io 包中。
inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
XGQ 2020-07-04
Andrewjdw 2020-05-29
Yakamoz 2020-05-26
行吟阁 2020-05-18
88491874 2020-04-30
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16

