首页 > 编程 > Java > 正文

Javaweb中使用Jdom解析xml的方法

2019-11-26 13:47:11
字体:
来源:转载
供稿:网友

一、前言

Jdom是什么?

Jdom是一个开源项目,基于树形结构,利用纯java的技术对XML文档实现解析,生成,序列化以及多种操作。它是直接为java编程服务,利用java语言的特性(方法重载,集合),把SAX和DOM的功能结合起来,尽可能的把原来解析xml变得简单,我们使用Jdom解析xml会是一件轻松的事情。

Jdom的优点:

1、Jdom专用于java技术,比Dom应用占用更少内存。

2、Jdom提供更加简单和逻辑性访问xml信息的基础方法

3、除xml文件外,Jdom还可以访问其他的数据源,例如可以创建类从SQL查询结果中访问数据

Jdom的构成:

Jdom由6个包构成

Element类表示XML文档的元素

org.jdom:      解析xml文件所要用到的基础类

org.jdom.adapters: 包含DOM适配的Java类

org.jdom.filter:    包含xml文档的过滤类

org.jdom.input:   包含读取XML文档的Java类

org.jdom.output: 包含输出XML文档的类

org.jdom.trans form: 包含将Jdom xml文档接口转换为其他XML文档接口的Java类

xml是什么?

xml是一种广为使用的可扩展标记语言,java中解析xml的方式有很多,最常用的像jdom、dom4j、sax等等。

Jdom包下载:http://www.jdom.org/downloads/index.html

这里笔者代码做的是使用java创建一个xml和读取一个xml,仅作为笔记介绍。

二、操作

下载jdom包,解压文件jdom-2.0.6.jar,jdom-2.0.6-javadoc.jar,将包导入到lib文件夹下。(注,如果有错误的话,将Jdom中的包全部导入)

例子1:使用jdom创建一个xml文件,名字为people.xml

新建类CareateJdom

package com.book.jdom;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;//生成xml文件public class CreateJdom {public static void main(String[] args) {//定义元素Element people,student;people = new Element("people");student = new Element("student");//设置属性student.setAttribute("name", "张三");student.setAttribute("salary","8000");//设置文本student.setText("呵呵");//将其添加到根目录下people.addContent(student);//新建一个文档。Document doc = new Document(people);//读取格式,赋值给当前的FormatFormat format = Format.getCompactFormat();//对当前格式进行初始化format.setEncoding("UTF-8");//设置xml文件缩进4个空格format.setIndent(" ");//建一个xml输出工厂,将格式给工厂XMLOutputter xmlout = new XMLOutputter(format);try {//将其写好的文本给工厂,并且建一个文件输出流,将数据输出xmlout.output(doc, new FileOutputStream("people.xml"));System.out.println("成功!");} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*运行结果:<?xml version="1.0" encoding="UTF-8"?><people><student name="张三" salary="8000" /></people>* */

例子2:使用Jdom解析people.xml文件

新建Readxml类

package com.book.jdom;import java.io.IOException;import java.util.List;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;//读取people.xml文档public class Readxml {public static void main(String[] args) {//新建构造器解析xmlSAXBuilder sax = new SAXBuilder();//建一个文档去接受数据Document doc;try {//获取people.xml文档doc = sax.build("people.xml");//获得根节点Element people = doc.getRootElement();//获得根节点下的节点数据List<Element> list = people.getChildren();for(int i = 0;i<list.size();i++){Element e = list.get(i);//获得属性值System.out.println("name:"+e.getAttributeValue("name")+" salary:"+e.getAttributeValue("salary"));//获得文本值System.out.println(e.getText());}} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}/** 运行结果:* name:张三 salary:8000呵呵* */

解析xml

用jdom获取多个相同标签名的不同属性值的方法<?xml version="1.0" encoding="UTF-8"?><Configuration>    <Key Name="China">      <Value Name="TextKey">China</Value>      <Value Name="Enabled">true</Value>      <Value Name="PhotoIDWidth">38PhotoIDWidth</Value>      <Value Name="PhotoIDHeight">38</Value>      <Key Name="Adult">        <Value Name="CrownPercent">0.10</Value>        <Value Name="HeadPercent">0.60AdultHeadPercent</Value>      </Key>      <Key Name="Child">        <Value Name="CrownPercent">0.10</Value>        <Value Name="HeadPercent">0.60ChildHeadPercent</Value>      </Key>    </Key>    <Key Name="Australia">      <Value Name="TextKey">Australia</Value>      <Value Name="Enabled">true</Value>      <Value Name="PhotoIDWidth">35PhotoIDWidth</Value>      <Value Name="PhotoIDHeight">45</Value>      <Key Name="Adult">        <Value Name="CrownPercent">0.061</Value>        <Value Name="HeadPercent">0.756"Adult"HeadPercent</Value>      </Key>      <Key Name="Child">        <Value Name="CrownPercent">0.072</Value>        <Value Name="HeadPercent">0.711ChildHeadPercent</Value>      </Key>    </Key>    <Key Name="Austria">      <Value Name="TextKey">Austria</Value>      <Value Name="Enabled">true</Value>      <Value Name="PhotoIDWidth">35PhotoIDWidth</Value>      <Value Name="PhotoIDHeight">45</Value>      <Key Name="Adult">        <Value Name="CrownPercent">0.064</Value>        <Value Name="HeadPercent">0.744AdultHeadPercent</Value>      </Key>      <Key Name="Child">        <Value Name="CrownPercent">0.078</Value>        <Value Name="HeadPercent">0.689ChildHeadPercent</Value>      </Key>    </Key></Configuration>package input;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;public class ReadXML {  /**   * @param args   */  public static void main(String[] args) throws JDOMException, IOException {    SAXBuilder sb = new SAXBuilder();    //构造文档对象    Document doc = sb.build(Test.class.getClassLoader().getResourceAsStream("nation.xml"));    //获取根元素    Element root = doc.getRootElement();    //定位到<Configuration> -> <Key>    List<Element> list = root.getChildren("Key");    List<Element> children = new ArrayList<Element>();    List<Element> childrens = new ArrayList<Element>();    for (int i = 0; i < list.size(); i++) {      Element element = (Element) list.get(i);      System.out.print(element.getAttributeValue("Name"));      //定位到<Configuration> -> <Key> -> <Value>      children = element.getChildren("Value");       for(int j=0; j<children.size(); j++){        Element elementChildren = (Element) children.get(j);        //定位到<Configuration> -> <Key> -> <Value Name="PhotoIDWidth">        if(elementChildren.getAttributeValue("Name").equals("PhotoIDWidth")){          //获取<Configuration> -> <Key> -> <Value Name="PhotoIDWidth"> 属性值          System.out.print("<--------->"+elementChildren.getAttributeValue("Name"));          //获取<Configuration> -> <Key> -> <Value Name="PhotoIDWidth"> 标签里内容          System.out.print(","+elementChildren.getText());        }      }      children.clear();      //定位到<Configuration> -> <Key> -> <Key>      children = element.getChildren("Key");      for(int j=0; j<children.size(); j++){        Element elementChildren = (Element)children.get(j);        //定位到<Configuration> -> <Key> -> <Key Name="Child">        if(elementChildren.getAttributeValue("Name").equals("Child")){          //定位到<Configuration> -> <Key> -> <Key Name="Child"> -> <Value>          childrens = elementChildren.getChildren("Value");          for(int k=0; k<childrens.size(); k++){            Element elementChildrens = (Element)childrens.get(k);            //定位到<Configuration> -> <Key> -> <Key Name="Child"> -> <Value Name="HeadPercent">            if(elementChildrens.getAttributeValue("Name").equals("HeadPercent")){              System.out.println("<--------->"+elementChildrens.getText());            }          }        }      }    }  }}打印结果:China<--------->PhotoIDWidth,38PhotoIDWidth<--------->0.60ChildHeadPercentAustralia<--------->PhotoIDWidth,35PhotoIDWidth<--------->0.711ChildHeadPercentAustria<--------->PhotoIDWidth,35PhotoIDWidth<--------->0.689ChildHeadPercent

以上所述是小编给大家介绍的Javaweb中使用Jdom解析xml的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表