java 的jdom使用类

80酷酷网    80kuku.com

  dom 

/*************************************************************
* 功能完成对xml文件的 建立,增,删,改,显示,查找(值比对)
* 现在只支持二级标签生成
* <根>
*   <一级标签>
*     <二级标签>值<二级标签/>
*     <二级标签>值<二级标签/>
*   <一级标签/>
* <根/>
* main()         为使用小样
* **************************************************************
* author        sanshi
* Create         2005/06/09
* 感谢:          张山,梅春,花开石头(任何帮助:包括精神虐待和肉体蹂躏)
* ***************************************************************
* param fileName 文件名
* param create   文件不存在是否建立,默认为false(不建立)
* param root     建立文件使用,代表根元素
* param child    建立文件使用,代表一级标签
* param twoChild 建立文件使用,代表二级标签。样式a[0][0]="标签名",a[0][1]="标签值"
* param debug    是否打印调试信息,对整个类有作用,默认为false不打印
*/

import org.jdom.output.XMLOutputter;
import org.jdom.Document;
import org.jdom.Element;

import java.util.List;
import org.jdom.output.Format;
import org.jdom.input.SAXBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;

public class XMLWork {
  private String fileName; //文件名
  private boolean create = false; //文件不存在是否建立
  private String root; //xml的根
  private String child; //一级标签
  private String[][] twoChild; //二级标签
  private boolean debug = true; //是否打印调试信息

/**********************调试开始***********************************/
  public static void main(String args[]) {
    String[][] a = new String[2][2];
    a[0][0] = "name";
    a[0][1] = "sanshi";
    a[1][0] = "count";
    a[1][1] = "1";
    XMLWork t = new XMLWork();
    t.XMLWork("zl.xml", 2, true); //第一步设置参数
    t.setTga("root", "child", a); //建立文件设置标签
    //t.creatXMLFile();
    String[] value = new String[2];
    value[0] = "sanshi";
    value[1] = "3";
    t.showAllElement(1,0);//

    if(t.isFindElement(value))
    {
      System.out.println("找到了!");
    }else{
      System.out.println("没找到!");
    }
    //t.editXMLElement(0,value);
    //t.addXMLElement(value);
    //t.delectXMLElement(0);
  }
/*************************调试结束*******************************/

  /**
   * 设置是否打印调试信息
   * param boolean debug false/不打印 ture/打印
   */
  public void setDebug(boolean debug) {
    this.debug = debug;
  }

  /**
   * 取得当前的调试信息
   * return boolean
   */
  public boolean getDebug() {
    return debug;
  }

  //判断文件名和一些常用变量是否存在
  public boolean isTrue() {
    boolean check = true;
    if (fileName == null || root == null || child == null ||
        twoChild.length <= 0) {
      check = false;
    }
    return check;
  }

  //初始化
  public XMLWork() {}

  /**
   * 判断输入文件名的合法性
   * param String  fileName  文件名字/打开或者建立
   * param int     list      二级标签的大小
   * param booleam crrate    如果不存在是否建立新文件
   */
  public void XMLWork(String fileName, int list, boolean create) {
    if (fileName == null || fileName.length() <= 0) {
      System.out.println("你没有输入文件名");
      System.exit(0);
    }
    else if (fileName.indexOf(".xml") <= 0) {
      System.out.println("你输入文件名不正确");
      System.exit(0);
    }
    else {
      this.fileName = fileName;
      this.create = create;
      String[][] children = new String[list][list];
      this.twoChild = children;
      //调试信息输出
      if (debug) {
        System.out.println("文件名设置成功=====>" + fileName);
        System.out.println("二级标签共有=======>" + list + "个");
      }
    }
  }

  //标签设置
  public void setTga(String root, String child, String[][] twoChild) {
    if (root == null || child == null) {
      System.out.println("你没有输入根标签或者是一级标签");
      System.exit(0);
    }
    else if (twoChild.length <= 0) {
      System.out.println("你没有输入二级标签");
      System.exit(0);
    }
    else {
      this.root = root;
      this.child = child;
      this.twoChild = twoChild;
      if (debug) { //调试信息输出
        System.out.println("标签设置成功!");
        System.out.println("根标签为==>" + root);
        System.out.println("一级标签为==>" + child);
        System.out.println(twoChild[0][0] + "====>" + twoChild[0][1]);
        System.out.println(twoChild.length);
      }
    }
  }

  //判断您传递近来的文件是否为有效
  private boolean isFile() {
    File file = new File(fileName);
    return file.exists();
  }

  public void printDebug() {
    if (!isTrue()) {
      System.out.println("缺少参数");
      System.exit(0);
    }
    if (isFile()) {
      //System.out.println("文件文法打开");
      //System.exit(0);
    }
  }

  public void creatXMLFile() {
    printDebug();
    //这以下根据需求更改------开始
    Element newroot = new Element(root); //设置根标签
    Element newchild = new Element(child); //设置单元标签//根下一级
    for (int i = 0; i < twoChild.length; i++) {
      Element count = new Element(twoChild[i][0]); //根下二级
      count.setText(twoChild[i][1]); //设置二级标签的值<二级标签>值<二级标签/>
      //count.setAttribute( "属性名", "属性值" );//添加一个属性
      newchild.addContent(count); //把二级添加到一级
    }
    newroot.addContent(newchild); //把一级添加到根
    Document doc = new Document(newroot); //把根写到document
    //设置生成wml
    //doc.setDocType(new DocType("wml","-//WAPFORUM//DTD WML 1.1//EN","http://www.wapforum.com/DTD/wml_1.1.xml"));
    //根据需求更改结束
    XMLOutputter xmlOut = new XMLOutputter(); //生成xml的输出流
    Format format = xmlOut.getFormat(); //把输出流格式化
    format.setEncoding("GBK"); //设置字符集
    format.setExpandEmptyElements(true); //是否填充
    xmlOut.setFormat(format); //把格式化的流给输出流
    try {
      //生成xml的文件,文件名为用户输入的文件
      xmlOut.output(doc, new FileOutputStream(fileName));
      System.out.println("文件建立成功文件名===>" + fileName);
    }
    catch (IOException ex) {
      System.out.println("file create failing" + ex.getMessage());
    }
  }

  /**
   * 此方法只是增加固定标签的值,在最后添加,如果文件不存在,而同意建立的话话建立
   * param String[] value 添加值的数组,按二级标签顺序存放
   */
  public void addXMLElement(String[] value) {
    printDebug();
    if (!this.isFile() && create) { //打开失败建立
      creatXMLFile();
    }
    //开始添加
    FileInputStream fi = null; //文件输入流
    FileOutputStream fo = null; //文件输出流
    File file = new File(fileName);
    try {
      fi = new FileInputStream(file); //建立打开流
      SAXBuilder sb = new SAXBuilder();
      Document doc = sb.build(fi); //把文件流给build
      Element root = doc.getRootElement(); //得到根元素
      List childsum = root.getChildren(); //得到根元素的集合
      Element newchild = new Element(child);
      for (int i = 0; i < twoChild.length; i++) {
        //生成新元素
        Element newcount = new Element(twoChild[i][0]);
        newcount.setText(value[i]);
        newchild.addContent(newcount); //在新根下添加新元素
      }
      childsum.add(newchild); //在xml文件里添加新的东西
      XMLOutputter xmlOut = new XMLOutputter();
      Format format = xmlOut.getFormat();
      format.setEncoding("GBK"); //设置字符集
      format.setExpandEmptyElements(true); //打开添加
      format.setIndent(" "); //设置分割符
      //format.setOmitDeclaration(true);//是否添加头信息
      xmlOut.setFormat(format);
      fo = new FileOutputStream(file);
      xmlOut.output(doc, fo);
      if (debug) {
        System.out.println("添加成功");
      }
    }
    catch (Exception e) {
      System.out.println("文件打开失败,文件名为:" + fileName + "<==>错误原因为:" +
                         e.getMessage());
    }
    finally {
      try {
        fi.close();
        fo.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 此方法删除指定的值,也就是xml中的第几个孩子
   * param ElementID  为孩子id。xml默认从0开始
   */
  public void delectXMLElement(int ElementID) {
    //printDebug();
    FileInputStream fi = null; //文件输入流
    FileOutputStream fo = null; //文件输出流
    File file = new File(fileName);
    try {
      if (!this.isFile()) { //文件打开失败
        System.out.println("文件打开失败,文件名为:" + fileName);
      }
      else {
        fi = new FileInputStream(file); //建立打开流
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build(fi); //把文件流给build
        Element root = doc.getRootElement(); //得到根元素
        List childsum = root.getChildren(); //得到根元素的集合
        if (ElementID >= childsum.size()) {
          System.out.println("超过长度!");
          System.exit(0);
        }
        childsum.remove(ElementID);
        XMLOutputter xmlOut = new XMLOutputter();
        Format format = xmlOut.getFormat();
        format.setEncoding("GBK"); //设置字符集
        format.setExpandEmptyElements(true); //打开添加
        format.setIndent(" "); //设置分割符
        //format.setOmitDeclaration(true);//是否添加头信息
        xmlOut.setFormat(format);
        fo = new FileOutputStream(file);
        xmlOut.output(doc, fo);
        if (debug) {
          System.out.println("删除成功");
        }
      }
    }
    catch (Exception e) {
      System.out.println("文件打开失败,文件名为:" + fileName + "<==>错误原因为:" +
                         e.getMessage());
    }
    finally {
      try {
        fi.close();
        fo.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 此方法编辑指定的值,也就是xml中的第几个孩子
   * param ElementID  为孩子id。xml默认从0开始
   * param value      数组为修改为的值
   */
  public void editXMLElement(int elementID, String[] value) {
    FileInputStream fi = null; //文件输入流
    FileOutputStream fo = null; //文件输出流
    try {
      if (!this.isFile()) { //文件打开失败
        System.out.println("文件打开失败,文件名为:" + fileName);
      }
      else {
        fi=new FileInputStream(fileName);//建立打开流
        SAXBuilder sb=new SAXBuilder();
        Document doc=sb.build(fi);//把文件流给build
        Element root=doc.getRootElement();//得到根元素
        List childsum=root.getChildren();//得到根元素的集合
        if (elementID >= childsum.size()) {
          System.out.println("超过长度!");
          System.exit(0);
        }
        Element edit=(Element)childsum.get(elementID);//选择编辑元素
        for(int i = 0; i < twoChild.length; i++){
          Element newname=edit.getChild(twoChild[i][0]);//生成新的标签
          newname.setText(value[i]);//设置新值
        }
        childsum.set(elementID,edit);//修改
        XMLOutputter xmlOut=new XMLOutputter();
       Format format=xmlOut.getFormat();
       //format.setEncoding("GBK");
       format.setExpandEmptyElements(true);
       format.setIndent(" ");
       //format.setOmitDeclaration(true);
       xmlOut.setFormat(format);
       fo=new FileOutputStream(fileName);
       xmlOut.output(doc,fo);
       if (debug) {
        System.out.println("编辑成功");
       }
      }
    }
    catch (Exception e) {
      System.out.println("文件打开失败,文件名为:" + fileName + "<==>错误原因为:" +
                         e.getMessage());
    }
    finally {
      try {
        fi.close();
        fo.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   *param int start     传入开始输出的项
   *param int end       结束输出的项,为0表示最后一个。
   */
  public void showAllElement(int start,int end)
  {
    FileInputStream fi = null; //文件输入流
    //FileOutputStream fo = null; //文件输出流
    try{
      if (!this.isFile()) { //文件打开失败
       System.out.println("文件打开失败,文件名为:" + fileName);
     }
      fi=new FileInputStream(new File(fileName));//建立打开流
      SAXBuilder sb=new SAXBuilder();
      Document doc=sb.build(fi);//把文件流给build
      Element root=doc.getRootElement();//得到根元素
      List childsum=root.getChildren();//得到根元素的集合

      if(childsum.size()==0)
      {
        System.out.println("该文件没有内容!文件名为===>"+fileName);
        System.exit(1);
      }

      if(end==0)
      {
        end=childsum.size();
      }
      if(start<0||end>childsum.size()||start==end||start>end)
      {
        System.out.println("输入参数有错误==>start="+start+"||==>end="+end);
        System.exit(0);
      }
      for(int i=start;i<end;i++)
      {
           Element ch=(Element)childsum.get(i);
           for(int j=0;j<twoChild.length;j++)
           {
             String p = ch.getChild(twoChild[j][0]).getText();
             System.out.println(p);
           }
      }
      if(debug)
      {
        System.out.println("输出完成");
      }
    }catch (Exception e) {
      System.out.println("文件打开失败,文件名为:" + fileName + "<==>错误原因为:" +
                         e.getMessage());
    }
    finally {
      try {
        fi.close();
        //fo.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   *param String[]  value   为比对的值对
   * return boolean         是否查找成功
   * */
  public boolean isFindElement(String[] value)
  {
    FileInputStream fi = null; //文件输入流
    //FileOutputStream fo = null; //文件输出流
     boolean count=true;
    try{
      if (!this.isFile()) { //文件打开失败
       System.out.println("文件打开失败,文件名为:" + fileName);
     }
      fi=new FileInputStream(new File(fileName));//建立打开流
      SAXBuilder sb=new SAXBuilder();
      Document doc=sb.build(fi);//把文件流给build
      Element root=doc.getRootElement();//得到根元素
      List childsum=root.getChildren();//得到根元素的集合

      if(childsum.size()==0)
      {
        System.out.println("该文件没有内容!文件名为===>"+fileName);
        System.exit(1);
      }

      for(int i=0;i<childsum.size();i++)
      {
        count=true;

           Element ch=(Element)childsum.get(i);
           for(int j=0;j<twoChild.length;j++)
           {
             String p = ch.getChild(twoChild[j][0]).getText();
             if(!p.equals(value[j]))
             {
               count=false;
             }
           }
           if(count)
           {
             return count;
           }
      }

      if(debug)
      {
        System.out.println("查找完成");
      }
    }
    catch (Exception e) {
      System.out.println("文件打开失败,文件名为:" + fileName + "<==>错误原因为:" +
                         e.getMessage());
    }

    finally {
      try {
        fi.close();
        //fo.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return count;
  }
}




分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: