JDOM与XML的案例(转帖)

JDOM与XML的案例转自:http://www.j2medev.com/code/j2se/language/200606/2559.html

××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import org.jdom.Comment;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.JDOMException;

import org.jdom.ProcessingInstruction;

import org.jdom.input.DOMBuilder;

import org.jdom.input.SAXBuilder;

import org.jdom.output.DOMOutputter;

/*

 * Simple demo of JDOM

 */

public class JDOMDemo {

    public static void main(String[] args) {

    // Must be at least one file or URL argument

        if (args.length == 0) {

            System.out.println("Usage: java JDOMDemo URL [...]");

        }

        SAXBuilder saxBuilder = new SAXBuilder();

        DOMBuilder domBuilder = new DOMBuilder();

        for (int i = 0; i < args.length; i++) {

            try {

                Document jdomDocument = saxBuilder.build(args[i]);

                DOMOutputter domOutputter = new DOMOutputter();

                /*

                 * Test getting DOM Document from JDOM Document

                org.w3c.dom.Document domDocument = domOutputter.output(doc);

                 */

                /*

                 * Test getting DOM Element from JDOM Element

                 */

                org.w3c.dom.Element domElement =

                  domOutputter.output(jdomDocument.getRootElement());

                /*

                 * Test getting JDOM Element from DOM Element

                 */

                org.jdom.Element jdomElement = domBuilder.build(domElement);

                demo(jdomElement);

            } catch (JDOMException e) { // indicates a well-formedness or other error

                System.out.println(args[i] + " is not a well formed XML document.");

                System.out.println(e.getMessage());

            } catch (IOException ex) {

        System.out.println("Input or Output error:" +

          args[i] + ": " + ex);

      }    

        }

    }

    public static void demo(Document doc) {

        List children = doc.getContent();

        Iterator iterator = children.iterator();

        while (iterator.hasNext()) {

            Object o = iterator.next();

            if (o instanceof Element) {

                demo((Element) o);

            }

            else if (o instanceof Comment)

        doComment((Comment) o);

            else if (o instanceof ProcessingInstruction)

        doPI((ProcessingInstruction) o);

        }

    }    

    public static void demo(Element element) {

    System.out.println("Element " + element);

        List attributes = element.getAttributes();

        List children = element.getContent();

        Iterator iterator = children.iterator();

        while (iterator.hasNext()) {

            Object o = iterator.next();

            if (o instanceof Element) {

                demo((Element) o);

            }

            else if (o instanceof Comment)

        doComment((Comment)o);

            else if (o instanceof ProcessingInstruction)

        doPI((ProcessingInstruction)o);

            else if (o instanceof String) {

                System.out.println("String: " + o);

            }  

        }

    } 

  public static void doComment(Comment c) {

    System.out.println("Comment: " + c);

  }

  public static void doPI(ProcessingInstruction pi) {

    System.out.println("PI: " + pi);

  }

}

// demo xml file

/*

<?xml version="1.0"?>

<people>

<person>

  <name>Ian Darwin</name>

  <email>http://www.darwinsys.com/</email>

  <country>Canada</country>

</person>

<person>

  <name>Another Darwin</name>

  <email type="intranet">afd@node1</email>

  <country>Canada</country>

</person>

</people>

*/

5 thoughts on “JDOM与XML的案例(转帖)”

  1. 不知怎么一回事,上面的示例程序编译通不过,说是下面这一段的output方法不匹配。我看了一下jdom.jar中的这个方法,明明是有的,真是怪。


    /*

    * Test getting DOM Element from JDOM Element

    */

    org.w3c.dom.Element domElement = domOutputter

    .output(jdomDocument.getRootElement());

    下面是从网上转的另一段代码。

    (转自:http://java.ccidnet.com/art/3737/20060731/706083_1.html)

    JAVA语言的开放性,吸引了很多公司和个人作者对JAVA的性能作不断地完善。JDOM 是两位著名的 Java 开发人员兼作者,Brett Mclaughlin 和 Jason Hunter 的创作成果,它致力于建立一个完整的基于 Java 平台的解决方案,通过 Java 代码来访问、操作并输出 XML 数据。

    JDOM可以从http://jdom.com网站上下载,目前最新的版本是beta9.0。

    一、用JDOM建立XML文档

    我们想建立一个形如下文的XML文档:1.xml

    <个人资料>

    <姓名 ID号=”2222”>张二

    <年龄>20

    我们先建立一个根元素和文档的实例,将根元素加入到文档中:

    Element root=new Element(“个人资料”);

    Document doc=new Document(root);

    加入子元素:

    Element name=new Element(“姓名”);

    Name.setAttribute(new Attribute(“ID号”,”2222”));

    Name.addContent(“张二”);

    Root.addContent(name);

    Element age=new Element(“年龄”);

    Age.addContent(“20”);

    Root.addContent(age);

    因为addContent()方法返回值为Element类型,上面的代码也可以写成:

    root.addContent(new Element("姓名").addContent("张二").setAttribute("ID号","2222"));

    root.addContent(new Element("年龄").addContent("20"));

    使用FileOutputStream,生成XML文本

    try

    {

    String ident=” ”; //子元素缩进两个空格

    Boolean isNew=true; //元素间有空行

    String cset=”gb2312”; //编码,显示中文

    XMLOutputter outer=new XMLOutputter(“ “,true,cset);

    Outer.output(doc.new FileOutputStream(“1.xml”));

    }catch(IOException e)

    {

    e.printStackTrace();

    }

    通过上面的代码,我们就生成了,如上所示的xml页面。

    从1.xml中取得相应的值:

    使用 SAXBuilder 对 1.xml进行语法分析

    try

    {

    SAXBuilder sb=new SAXBuilder();

    Document myDoc=sb.build(new FileInputStream(“1.xml”));

    }catch(JDOMException e)

    {

    e.printStackTrace();

    }catch(NullPointerException e)

    {

    e.printStackTrace();

    }

    访问子元素

    Element another=myDoc.getRootElement(); //先得到根元素

    Element nameE=root.getChild(“姓名”);

    System.out.println(nameE.getText());

    删除子元素

    boolean re=another.removeChild(“姓名”);

    //删除后,记得将文档重新写入一遍

  2. 我在上面例子的基础上用Format类格式化xml文件的输出,完整的源文件如下:


    import java.io.FileOutputStream;

    import java.io.IOException;

    import org.jdom.Attribute;

    import org.jdom.Document;

    import org.jdom.Element;

    import org.jdom.output.Format;

    import org.jdom.output.XMLOutputter;

    public class TestJdom {

    /**

    * @param args

    */

    public static void main(String[] args) {

    Element root = new Element("个人资料");

    Document doc = new Document(root);

    //加入子元素:

    Element name = new Element("姓名");

    name.setAttribute(new Attribute("ID号", "2222"));

    name.addContent("张二");

    root.addContent(name);

    Element age = new Element("年龄");

    age.addContent("20");

    root.addContent(age);

    //因为addContent()方法返回值为Element类型,上面的代码也可以写成:

    //root.addContent(new Element("姓名").addContent("张二").setAttribute("ID号","2222"));

    //root.addContent(new Element("年龄").addContent("20"));

    //使用FileOutputStream,生成XML文本

    try {

    XMLOutputter outer = new XMLOutputter(Format.getPrettyFormat());

    outer.output(doc, new FileOutputStream("1.xml"));

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    生成的xml文件如下:


    <?xml version="1.0" encoding="UTF-8"?>

    <个人资料>

      <姓名 ID号="2222">张二</姓名>

      <年龄>20</年龄>

    </个人资料>

    上面Format类的使用说明,来自jdom的apidoc:


    public class Format

    extends java.lang.Object

    implements java.lang.Cloneable

    Class to encapsulate XMLOutputter format options. Typical users can use the standard format configurations obtained by getRawFormat() (no whitespace changes), getPrettyFormat() (whitespace beautification), and getCompactFormat() (whitespace normalization).

    我觉得,我们举一个例子最好给出完整的源码,这样像我这样的生手也好少走弯路:)

  3. 真正到用时才发觉自己在xml方面知识的极度欠缺。虽然现在java中有各种现成的包可以用。但是如果对xml没有一个最起码的了解,运用这些工具还是困难的。比如用jdom处理命名空间(namespace)和标头,我就不知道该怎么用,在网上查了一下,好像也没有现成的例子。也许真要把xml的基础知识学一下了。

  4. 没有搞懂jdom写xml文件的用法,自己用一个土办法来写成了sitemap.xml,即用一个StringBuffer逐句把内容加进去,再写到文件里。我想这个方法实际应该比用jdom还要高效点吧,少了中间的处理环节。不过,这只是自己不会xml的权宜之计。碰到复杂的xml文件肯定还是要用那些开源的处理包才好。

    自己写的sitemap.xml放上去,已经被google系统验证为无错误了。经过询问“SEO每日一帖”的zac先生,最后还是把放了一晚上的sitemap.xml撤掉了。主要是怕不明其中的规则,误用其中的东西,结果反而不好。以后经过学习和实践,也许要恢复这个sitemap.xml文件也说不定。

Comments are closed.