XML解析示例

一:使用jdom创建XML文件。

 /*
 * 需要导入 jdom.jar 包。
 */
 public void creatXmlFile(Connection pConn,String pTableName){
      String mFileName = "c://people.xml";
      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;
      try{
        Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.100:1521:ORCL", "admin","12345678");
        stmt = conn.createStatement();
        rs   = stmt.executeQuery("SELECT * FROM t_user");
        ResultSetMetaData meta = rs.getMetaData();
        File       mFile       = new File(mFileName);
        mFile.createNewFile();
       
        BufferedWriter mWriter = new BufferedWriter(new FileWriter(mFile));
        mWriter.write("<root></root>");
        mWriter.close();

        SAXBuilder mBuilder    = new SAXBuilder();
        Document   mDocument   = mBuilder.build(mFile);
        Element    mRoot       = mDocument.getRootElement();
        Element    mTable      = new Element("table");
        String     mFieldName  = "";//临时变量,字段名称
        String     mFieldValue = "";//临时变量,字段值

        mTable.addAttribute("name",pTableName);
        mRoot.addContent(mTable);

        for(; rs.next();){
          Element    mField      = new Element("field");
          mTable.addContent(mField);
          for(int i = 1; i < meta.getColumnCount() + 1; i++){
            mFieldName  = meta.getColumnName(i).toUpperCase();
            if(rs.getString(i) == null){
              mFieldValue = "";
            }else if(meta.getColumnType(i) == java.sql.Types.DATE){
              mFieldValue = rs.getString(i).substring(0,19);
            }else{
              mFieldValue = rs.getString(i);
            }
            mField.addAttribute(mFieldName,mFieldValue);
          }
        }
        mTable.addContent("SUNSHUXIN");
       
        XMLOutputter outp = new XMLOutputter("",true,"GB2312");
        outp.output(mDocument, new FileOutputStream(mFile));
        System.out.println("生成xml文件成功!");

      }catch(Exception e){
        System.out.println("生成xml文件错误!");
        e.printStackTrace();
      }finally{
        try{
          if (conn != null)
            conn.close();
        }catch(Exception e)
        {}
      }
  }

 

二:使用dom4j解析并修改XML文件。

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

 

 /**
  *@param nodeNameOfList,节点在XML文件中的全路径, 例如:"//jspconfig/table/cols"
  * /

public static void updateXmlFile(String url,String nodeNameOfList){
  try{
   Document document = parseByFile(url);
   List list = document.selectNodes(nodeNameOfList);
   for(int i=0;i<list.size();i++){
     Element colsElement = (Element)list.get(i);
     colsElement.setAttributeValue("status","0");
   }
   write(document,getSrcProjectPath()+url);
  }catch(Exception e){
   e.printStackTrace();
  }
 }


  public static Document parseByFile(String fileName)
   throws DocumentException, MalformedURLException,
   FileNotFoundException {
  String path = getSrcProjectPath() + fileName;
  SAXReader reader = new SAXReader();
  Document document = null;
  document = reader.read(new FileInputStream(path), "UTF-8");
  return document;
 }

 

// lets write to a file
  public static void write(Document document,String path) throws IOException {


  OutputFormat of = OutputFormat.createPrettyPrint();
  of.setEncoding("utf-8");
  of.setExpandEmptyElements(false);
  of.setIndentSize(4);
       
        OutputStream out=new FileOutputStream(path);
        java.io.Writer wr=new OutputStreamWriter(out,"utf-8");  
        XMLWriter writer = new XMLWriter(wr,of );
        writer.write( document );
        writer.flush();
        writer.close();        
    }

 

    /**
     * 得到项目的类路径
     * @throws MalformedURLException
     */
 public static String getSrcProjectPath()
 {
  URL url = xmlUtil.class.getResource("");
  String temp=url.toString();
  String temp1 = temp.substring(0,temp.indexOf("classes")+"classes".length()).replace("file:/", "");
  return temp1;  
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值