JDOM读取XML,并且创建XML

本文介绍了一个Java程序如何使用JDOM库解析XML文件并创建新的XML文件的方法。程序首先读取源XML文件,利用JDOM解析XML,并将解析后的数据重新组织成一个新的XML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.brit.cx.common;

import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.sun.org.apache.xpath.internal.axes.HasPositionalPredChecker;


public class ST {
 
 private static List listParentName = new ArrayList();
 private static String topParentName="";
 public static void main(String[] args) throws IOException {
  doXmlAndCreate("e:/1.xml","e:/create.xml");
 }

 private static boolean doXmlAndCreate(String path,String newPath) throws IOException{
  boolean bflag = false;
  //创建xml
  Element Row = new Element("Row");
  
  if(path!=null||!path.equals("")){
   byte[] a = Util.readFile(path);
   List<HashMap<String, String>> listObj = conteverByJdom(a);//得到数据集合
   Element [] root = new Element[listObj.size()];
   
   System.out.println(listObj.size()+"多少个");
   for (int i = 0; i < listObj.size(); i++) {
    root[i]=new Element(topParentName);
    //得到HashMAP
    HashMap<String, String> map =  listObj.get(i);
    Set keySet = map.keySet();   
             Object[] keyArray =  keySet.toArray();  // 此数组存放所有的HashMap中的键名
             String[] keys = new String[keySet.size()];
             Vector<String>   v = new   Vector();   ;   
             for(int j = 0 ; j < keyArray.length ; j++){     
                  keys[j] = keyArray[j].toString();           
             }
             
             //主节点 listParentName存储的父节点名字取出来
            
             for (int j = 0; j < keys.length; j++) {
              root[i].addContent(create(keys[j], map.get(keys[j])));
             }
             Row.addContent(root[i]);
             
   }
   
   bflag = createXML(Row,newPath);
   
  }
  
  return bflag;
 }
 
 /**
  * 通过Jdom将对应属性。
  * @param content
  * @throws IOException 
  */
 private static List<HashMap<String, String>> conteverByJdom(byte[] content) throws IOException {
  
  List<HashMap<String, String>> listRootData = new ArrayList<HashMap<String, String>>();
  
  System.out.println("通过Jdom将对应属性。");
  SAXBuilder builder = new SAXBuilder();
  ByteArrayInputStream bais = new ByteArrayInputStream(content);
  Document doc; 
  try {
   doc = builder.build(bais);
   Element root = doc.getRootElement();
   System.out.println("1.   " + root.getName());
   Element dataobjects = root.getChild("dataobjects");
   System.out.println("2.   " + dataobjects.getName() + " "
     + dataobjects.getText());
   Element dOMessageWrapper = dataobjects
     .getChild("DOMessageWrapper__");
   System.out.println("3.   " + dOMessageWrapper.getName());
   Element row = dOMessageWrapper.getChild("Row");
   System.out.println("4.   " + row.getName());
   Element data = row.getChild("data");
   System.out.println("5.   " + data.getName() + " "
     + data.getText());
   List dataList = data.getChildren();
   System.out.println("父级"+dataList.size()+"个");
   
   if(dataList.size()>0){
    
    for (int i = 0; i < dataList.size(); i++) {
     HashMap map = new HashMap();
     
     Element elem1 = (Element) dataList.get(i);
     
     System.out.println("父级别"+elem1.getName());
     topParentName=elem1.getName();
     
     List dataList2 = elem1.getChildren();
     
      if(dataList2.size()>0){
      
        for (int j = 0; j < dataList2.size(); j++) {
         Element elem2 = (Element)dataList2.get(j);
         elem2.getName();
         System.out.println("子级别"+elem2.getName());
           
           //打印节点下的name和value
           String name=elem2.getName();
           String value=elem2.getText();
           System.out.println(name+"---"+value);
           
           if(name.indexOf("_")>-1){
            map.put(name.substring(name.indexOf("_")+1), value);
            topParentName = name.substring(0, name.indexOf("_"));
           }else{
            map.put(name, value);
           }
           
        }
        listRootData.add(map);
       
      }
     }
     
    }
  } catch (JDOMException e) {
   e.printStackTrace();
  }
  return listRootData;
 }
 
 /**
  * @author zg
  * @description 创建XML
  * @param el :Element对象,xml中需要创建的元素.
  * @param newXmlPath :创建的xml生成到硬盘上的真实的绝对路径.
  * @return boolean
  */
 public static boolean createXML(Element el,String newXmlPath){
     boolean result=false;
     Document doc = new Document();
     doc.setContent(el);
     doc.toString();
     FileWriter writer;
     XMLOutputter outputter=new XMLOutputter();
     try {
      writer = new FileWriter(newXmlPath);
      Format format = Format.getRawFormat();// getCompactFormat();  getPrettyFormat(); getRawFormat();--可以实现标签内如果为空,则后面跟这</XX>标签
      //设置XML编码类型
      format.setEncoding("UTF-8");
      //设置缩进字符串            
      format.setIndent("  ");
      outputter.setFormat(format);
      outputter.output(doc, writer);
      writer.close();
      return result=true;
      
     } catch (Exception e) {
      e.printStackTrace();
     }
     return result;
 }
 
 /**
  * @author zg
 * 创建新节点
 * @param name 节点的名称
 * @param text 节点的内容
 * @return Element元素对象
 */
 private static Element create(String name, String text) {
    return new Element(name).setText(text);
 }

 
 
}

 

 

 

 

package com.brit.cx.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Util {

public Util() {
}
/** *//**
   * 读取源文件内容
   * @param filename String 文件路径
   * @throws IOException
   * @return byte[] 文件内容
 * @throws IOException 
   */
public static byte[] readFile(String filename) throws IOException{

    File file =new File(filename);
    if(filename==null || filename.equals("")){
      throw new NullPointerException("无效的文件路径");
    }
    long len = file.length();
    byte[] bytes = new byte[(int)len];

    BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
    int r = bufferedInputStream.read( bytes );
    if (r != len)
      throw new IOException("读取文件不正确");
    bufferedInputStream.close();

    return bytes;

}

/** *//**
   * 将数据写入文件
   * @param data byte[]
 * @throws IOException 
 * @throws IOException
   */
public static void writeFile(byte[] data,String filename) throws IOException{
    File file =new File(filename);
    file.getParentFile().mkdirs();
    BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));
    bufferedOutputStream.write(data);
    bufferedOutputStream.close();

}

/** *//**
   * 从jar文件里读取class
   * @param filename String
   * @throws IOException
   * @return byte[]
 * @throws IOException 
   */
public byte[] readFileJar(String filename) throws IOException{
    BufferedInputStream bufferedInputStream=new BufferedInputStream(getClass().getResource(filename).openStream());
    int len=bufferedInputStream.available();
    byte[] bytes=new byte[len];
    int r=bufferedInputStream.read(bytes);
    if(len!=r){
      bytes=null;
      throw new IOException("读取文件不正确");
    }
    bufferedInputStream.close();
    return bytes;
}

/** *//**
   * 读取网络流,为了防止中文的问题,在读取过程中没有进行编码转换,而且采取了动态的byte[]的方式获得所有的 byte返回
   * @param bufferedInputStream BufferedInputStream
   * @throws IOException
   * @return byte[]
 * @throws IOException 
   */
public byte[] readUrlStream(BufferedInputStream bufferedInputStream) throws IOException{
    byte[] bytes = new byte[100];
    byte[] bytecount=null;
    int n=0;
    int ilength=0;
    while((n=bufferedInputStream.read(bytes))>=0){
      if(bytecount!=null)
        ilength=bytecount.length;
      byte[] tempbyte=new byte[ilength+n];
      if(bytecount!=null){
        System.arraycopy(bytecount,0,tempbyte,0,ilength);
      }

      System.arraycopy(bytes,0,tempbyte,ilength,n);
      bytecount=tempbyte;

      if(n<bytes.length)
        break;
    }
    return bytecount;
}

}

 

附件里有上传XML和 JDOM解析和创建XML的例子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值