zoukankan      html  css  js  c++  java
  • DOM4J 转载 规格严格

    java解析XML--dom4j

    java相关 2007-03-11 16:16:08 阅读7 评论0 字号:

    dom4j的主要接口:

    Attribute
    Attribute定义了XML的属性

    Branch
    Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为,

    CDATA
    CDATA 定义了XML CDATA 区域

    CharacterData
    CharacterData是一个标识借口,标识基于字符的节点。如CDATA,Comment, Text.

    Comment
    Comment 定义了XML注释的行为

    Document
    定义了XML文档

    DocumentType
    DocumentType 定义XML DOCTYPE声明

    Element
    Element定义XML 元素

    ElementHandler
    ElementHandler定义了 Element 对象的处理器

    ElementPath
    被 ElementHandler 使用,用于取得当前正在处理的路径层次信息

    Entity
    Entity定义 XML entity

    Node
    Node为所有的dom4j中XML节点定义了多态行为

    NodeFilter
    NodeFilter 定义了在dom4j节点中产生的一个滤镜或谓词的行为(predicate)

    ProcessingInstruction
    ProcessingInstruction 定义 XML 处理指令.

    Text
    Text 定义XML 文本节点.

    Visitor
    Visitor 用于实现Visitor模式.

    XPath
    XPath 在分析一个字符串后会提供一个XPath 表达式

    1. 读取并解析XML文档: 

    从文件读取XML,输入文件名,返回XML文档

    public Document read(String fileName) throws MalformedURLException, DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(fileName));
        return document;
    }

    其中,reader的read方法是重载的,可以从InputStream, File, Url等多种不同的源来读取。得到的Document对象就带表了整个XML。

    2. 取得Root节点 

    public Element getRootElement(Document doc){
        return doc.getRootElement();

    3. 遍历XML树
    DOM4J提供至少3种遍历节点的方法:

    1) 枚举(Iterator) 

    // 枚举所有子节点

    for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
        Element element = (Element) i.next();
        // do something
    }

    // 枚举名称为foo的节点

    for ( Iterator i = root.elementIterator(foo); i.hasNext();){

        Element foo = (Element) i.next();
        // do something
    }

    // 枚举属性

    for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
        Attribute attribute = (Attribute) i.next();
        // do something
    }

     2)递归

    递归也可以采用Iterator作为枚举手段,但文档中提供了另外的做法

    public void treeWalk() { 
        treeWalk(getRootElement());
    }

    public void treeWalk(Element element) { 
        for (int i = 0, size = element.nodeCount(); i < size; i++) { 
            Node node = element.node(i); 
            if (node instanceof Element) { 
               treeWalk((Element) node); 
            } else { 
            // do something....
           }
       }
    }

    3) Visitor模式

    需要自定一个类实现Visitor接口

    public class MyVisitor extends VisitorSupport { 
        public void visit(Element element){ 
            System.out.println(element.getName()); 
        } 
        public void visit(Attribute attr){ 
            System.out.println(attr.getName()); 
        }
    }

    调用: root.accept(new MyVisitor())

    Visitor接口提供多种Visit()的重载,根据XML不同的对象,将采用不同的方式来访问。上面是给出的Element和Attribute的简单实现,一般比较常用的就是这两个。

    注意:这个Visitor是自动遍历所有子节点的。如果是root.accept(MyVisitor),将遍历子节点

    4. XPath支持
    DOM4J对XPath有良好的支持,如访问一个节点,可直接用XPath选择。

    public void bar(Document document) { 
        List list = document.selectNodes( //foo/bar ); 
        Node node = document.selectSingleNode(//foo/bar/author); 
        String @name );
    }

    5. 字符串与XML的转换

    有时候经常要用到字符串转换为XML或反之,
    // XML转字符串
    Document document = ...;
    String text = document.asXML();

    // 字符串转XML
    String text = James ;
    Document document = DocumentHelper.parseText(text);

    6 用XSLT转换XML
    public Document styleDocument( 
        Document document, 
        String stylesheet
    ) throws Exception {
    // load the transformer using JAXP 
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer transformer = factory.newTransformer(
       new StreamSource( stylesheet );
    )
    // now lets style the given document
       DocumentSource source = new DocumentSource( document );
       DocumentResult result = new DocumentResult();
       transformer.transform( source, result );
    // return the transformed document
       Document transformedDoc = result.getDocument();
       return transformedDoc;
    }

    7. 创建XML
    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(root);
        Element author1 = root
                              .addElement(author)
                              .addAttribute(name, James) 
                              .addAttribute(location, UK)
                              .addText(James Strachan);
        Element author2 = root
                              .addElement(author)
                              .addAttribute(name, Bob)
                              .addAttribute(location, US)
                              .addText(Bob McWhirter); 
       return document;
    }

    8. 文件输出
    一个简单的输出方法是将一个Document或任何的Node通过write方法输出
    FileWriter out = new FileWriter( foo.xml );
    document.write(out);

    如果想改变输出的格式,比如美化输出或缩减格式,可以用XMLWriter类
    public void write(Document document) throws IOException {
     // 指定文件
        XMLWriter writer = new XMLWriter( new FileWriter( output.xml ) );
        writer.write( document );
        writer.close();
    // 美化格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    // 缩减格式
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }

  • 相关阅读:
    spring原理
    mybatis原理
    数据结构与算法
    JVM内存模型及垃圾回收算法
    dorado动态修改数据验证
    dorado在dialog中使用js通过控件id修改控件值,值闪烁一下消失问题
    由于;引发的Oracle的BadSqlExecption
    swagger配置
    SpringBoot整合mybatis碰到的问题
    关于浏览器的自动缓存问题
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/1792343.html
Copyright © 2011-2022 走看看