DOM4J---XML处理

来源:互联网 发布:淘宝上理肤泉是正品吗 编辑:程序博客网 时间:2024/05/22 06:20

DOM

  • 概念

    文档对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展标志语言的标准编程接口.在网页上,组织页面(或文档)的对象被组织在一个树形结构中,用来表示文档中对象的标准模型就称为DOM

  • W3C DOM 标准被分为 3 个不同的部分:

    核心 DOM - 针对任何结构化文档的标准模型
    XML DOM - 针对 XML 文档的标准模型
    HTML DOM - 针对 HTML 文档的标准模型

  • 节点

    文本节点 document
    元素节点 < p >
    文本节点
    属性节点
    注释节点

DOM4J

  • 概念

    dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的。dom4j是一个十分优秀的JavaXML API,具有性能优异、功能强大和极其易使用的特点

  • 主要接口定义

接口名称 描述 Attribute XML的属性 CDATA XML CDATA 区域 Comment XML注释的行为 Document XML文档 Element XML 元素 DocumentType XML DOCTYPE声明 Entity XML entity Node 为所有的dom4j中XML节点定义了多态行为 Text XML文本节点. ProcessingInstruction 定义 XML 处理指令. Visitor 用于实现Visitor模式. XPath 在分析一个字符串后会提供一个XPath表达式
  • 需要jar包
<dependency>    <groupId>dom4j</groupId>    <artifactId>dom4j</artifactId>    <version>1.6.1</version></dependency><dependency>      <groupId>jaxen</groupId>      <artifactId>jaxen</artifactId>      <version>1.1.6</version>  </dependency>
  • 方法

  • 读取xml文件

SAXReader reader = new SAXReader();Document document = reader.read(new File(fileName));
  • Visitor模式
    public class XMLVisit extends VisitorSupport {        public void visit(Document document) {        }        public void visit(DocumentType documentType) {        }        public void visit(Element node) {        }        public void visit(Attribute node) {        }        public void visit(CDATA node) {        }        public void visit(Comment node) {        }        public void visit(Entity node) {        }        public void visit(Namespace namespace) {        }          public void visit(ProcessingInstruction node) {        }        public void visit(Text node) {        }        public void visit(Text node) {        }    }    document.accept(new XMLVisit());
  • XPath模式
List list = document.selectNodes( //foo/bar );Node node = document.selectSingleNode(//foo/bar/author);String name = node.valueOf( @name );

XPath详细使用可查看: W3C

http://www.runoob.com/xpath/xpath-tutorial.html

  • 文件输出
//简单输出FileWriter out = new FileWriter( foo.xml );document.write(out);//指定文件XMLWriter writer = new XMLWriter(new FileWriter( output.xml));writer.write( document );writer.close();//美化格式OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("UTF-8");writer = new XMLWriter( System.out, format );writer.write( document );//缩减格式format = OutputFormat.createCompactFormat();format.setEncoding("UTF-8");writer = new XMLWriter( System.out, format );writer.write( document );}

具体的方法,api的方法名称描述的很清楚。直接编写就行,多用多练就ok了。