当前位置: 首页 > news >正文

xml文件操作(利用dom4j)

 

 

闲着无事,研究了一下dom4j,写了个对xml操作的类。
代码:
package dom_xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import java.util.List;
import java.util.Iterator;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.*;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.DocumentHelper;

public class XmlDom4J {

/**
  * 生成xml文件;
  *
  */
public void createXMLFile(){
  //使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。
  Document document=DocumentHelper.createDocument();
 
  //使用 addElement() 方法创建根元素 catalog 。addElement() 用于向 XML 文档中增加元素。
  Element catalogElement = document.addElement("catalog");
  //在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。
  catalogElement.addComment("An XML Catalog");
  //在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。
  catalogElement.addProcessingInstruction("target","text");
 
  //在 catalog 元素中使用 addElement() 方法增加 journal 元素。
  Element journal=catalogElement.addElement("journal");
  //使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。
  journal.addAttribute("title", "XML Zone");
  journal.addAttribute("publisher", "IBM Devoloperment");
 
  //添加节点journal的子节点article,并设置其属性;
  Element articleElement=journal.addElement("article");
  articleElement.addAttribute("level", "Intermediate");
  articleElement.addAttribute("date", "December-2008");
 
  //添加节点articleElement的子结点title,并使用 setText() 方法设置其元素的文本。
  Element titleElement=articleElement.addElement("title");
  titleElement.setText("又是下雨天");
 
  //添加节点articleElement的子结点author.添加子结点的子结点firstname、lastname,并设置其文件;
  Element authorElement=articleElement.addElement("author");
     Element  firstNameElement=authorElement.addElement("firstname");
     firstNameElement.setText("Marcello");
     Element lastNameElement=authorElement.addElement("lastname");
     lastNameElement.setText("Vitaletti");
    
     //可以使用 addDocType()  方法添加文档类型说明。
   
    
     XMLWriter output;
  try {
   OutputFormat format=new OutputFormat();
   format.setEncoding("gb2312");
   output = new XMLWriter(
     new FileWriter(new File("catalog.xml")),format);
   output.write(document);
   output.close();
  } catch (IOException e) {
   e.printStackTrace();
  } 
}

/**
  * 修改xml文件指定节点的属性;
  * @param inputXml xml文件流
  * @oldAttributeValue 原属性;
  * @attributeValue 要修改成的值;
  * @param XPath 要修改节点属性的表达式;如:"//article/@level" 则表示修改节点level(父节点为article)的属性
  * 特别说明:@后面表示的是属性;
  */
public Document modifyXMLNodeAttributeByName(File inputXml, String XPath,String oldAttributeValue,String attributeValue) {
  if(XPath.indexOf("@")<0){
   System.out.println("参数XPath无效,请在要修改的属性前加入'@'");
   return null;
  }
  SAXReader saxReader = new SAXReader();
  Document document=null;
  try {
   document = saxReader.read(inputXml);
   List list = document.selectNodes(XPath);
   Iterator iter = list.iterator();
   while (iter.hasNext()) {
    Attribute attribute = (Attribute) iter.next();
    if (attribute.getValue().equals(oldAttributeValue))//把原属性修改为新的属性;
     attribute.setValue(attributeValue);
   }
   
  } catch (DocumentException e) {   
   e.printStackTrace();
  }
  return document;
 
}

/**
  * 修改指定节点的属性值;
  * @param inputXml xml文件流
  * @param XPath 要修改节点属性的表达式;如:"//article/@level" 则表示修改节点level(父节点为article)的属性
  * @param attributeValue 属性新值;
  */
public Document modifyXMLNodeAttributeByName(File inputXml, String XPath,String attributeValue) {
  if(XPath.indexOf("@")<0){
   System.out.println("参数XPath无效,请在要修改的属性前加入'@'");
   return null;
  }
  SAXReader saxReader = new SAXReader(); 
  Document document=null;
  try {
   document = saxReader.read(inputXml); 
   List list = document.selectNodes(XPath);   
   Iterator iter = list.iterator();
   while (iter.hasNext()) {
    Attribute attribute = (Attribute) iter.next();   
    //把原属性修改为新的属性;
    attribute.setValue(attributeValue);
   }
   
  } catch (DocumentException e) {   
   e.printStackTrace();
  }
  return document;
}

/**
  * 获取某一节点的属性值;
  * @param inputxml xml文件;
  * @param XPath
  * @return
  */
public String[] getNodeAttributeValue(File inputxml,String XPath){
  String nodeAttri="";//储存节点属性值;
  if(XPath.indexOf("@")<0){
   return null;
  }
  SAXReader saxReader=new SAXReader();
  Document document=null;
  try{
   document=saxReader.read(inputxml);
   List list=document.selectNodes(XPath);
   Iterator it=list.iterator();
   while(it.hasNext()){
    Attribute attri=(Attribute)it.next();
    nodeAttri+=attri.getValue()+",";
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  if(nodeAttri.length()>0){
   nodeAttri=nodeAttri.substring(0, nodeAttri.length()-1);
  }
  return nodeAttri.split(",");
}

/**
  * 修改指定节点的文本值;
  * @param inputXml
  * @param XPath 要修改节点属性的表达式;如:"//article/@level" 则表示article节点下的所有level节点的文本;
  * @param newText 新的文本值;
  */
public Document modifyXMLNodeTextByName(File inputXml,String XPath,String newText){
  if(XPath.indexOf("@")>=0){
   System.out.println("参数XPath无效!");
   return null;
  }
  SAXReader saxReader = new SAXReader();
  Document document=null;
  try {
   document=saxReader.read(inputXml);
   List list= document.selectNodes(XPath);
   Iterator iter = list.iterator();
   while(iter.hasNext()){   
    Element elementText=(Element)iter.next();   
    elementText.setText(newText);   
   }
  } catch (DocumentException e) {   
   e.printStackTrace();
  }
  return document;
}

/**
  *  替换指定节点文本的值。
  * @param inputXml xml文件流
  * @param XPath 要修改节点属性的表达式;如:"//article/level" 则表示article节点下的所有level节点的文本;
  * @param oldText 原文本
  * @param newText 新文本;
  */
public Document modifyXMLNodeTextByName(File inputXml,String XPath,String oldText,String newText){
  if(XPath.indexOf("@")>=0){
   System.out.println("参数XPath无效!");
   return null;
  }
  SAXReader saxReader = new SAXReader();
  Document document=null;
  try {
   document=saxReader.read(inputXml);
   List list= document.selectNodes(XPath);
   Iterator iter = list.iterator();
   while(iter.hasNext()){
    Element elementText=(Element)iter.next();
    if(elementText.getText().equals(oldText))
    elementText.setText(newText);
   }
  } catch (DocumentException e) {   
   e.printStackTrace();
  }
  return document;
}
/**
  * 获取某一节点的文本内容;
  * @param inputxml xml文件;
  * @param XPath
  * @return
  */
public String[] getNodeTextValue(File inputxml,String XPath){
  String nodeTextValue="";//储存节点属性值;
  if(XPath.indexOf("@")>=0){
   return null;
  }
  SAXReader saxReader=new SAXReader();
  Document document=null;
  try{
   document=saxReader.read(inputxml);
   List list=document.selectNodes(XPath);
   Iterator it=list.iterator();
   while(it.hasNext()){
    Element text=(Element)it.next();
    nodeTextValue+=text.getText()+",";
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  if(nodeTextValue.length()>0){
   nodeTextValue=nodeTextValue.substring(0, nodeTextValue.length()-1);
  }
  return nodeTextValue.split(",");
}



/**
  * 保存xml文件;
  * @param document xml文件流;
  * @param filePath 文件存储的全路径(包括文件名)
  * @code 储存的编码;
  */
public void saveXmlFile(Document document,String filePath,String code){
  if(document==null){
   return ;
  }
  XMLWriter output;
  try {
   OutputFormat format=new OutputFormat();
   format.setEncoding(code);
   output = new XMLWriter(new FileWriter(new File(filePath)),format);
   output.write( document );
   output.close();
  } catch (IOException e) {   
   e.printStackTrace();
  } 
}
 
  // 测试;
public static void main(String[] args){
  XmlDom4J dom4jParser=new XmlDom4J(); 
  //生成XML
  //dom4jParser.createXMLFile();
  File file=new File("D:/MyWork/operateXMLfile/catalog.xml");
  //dom4jParser.saveXmlFile(document, "F://test.xml", "GBK");
 
  /*String[] attrArray=dom4jParser.getNodeAttributeValue(file, "//article/@level");
  if(attrArray!=null){
   for(int i=0;i<attrArray.length;i++){
    System.out.println("Attribute is :"+attrArray[i]);
   }
  }*/
 
  String[] nodeText=dom4jParser.getNodeTextValue(file, "//article/title");
  if(nodeText!=null){
   for(int i=0;i<nodeText.length;i++){
    System.out.println("NODE TEXT IS:"+nodeText[i]);
   }
  }
 
}
}
xml文件定义如下:
代码:
<?xml version="1.0" encoding="gb2312"?>
<catalog><!--An XML Catalog--><?target text?>
<journal title="XML Zone" publisher="IBM Devoloperment">
<article level="小学四年级"  date="December-2008"><title>又是下雨天</title>
<author><firstname>Marcello</firstname><lastname>Vitaletti</lastname></author></article>
<article level="大学四年级"  date="2008-04-01"><title>太阳出来了</title>
<author><firstname>Marcello</firstname><lastname>Vitaletti</lastname></author></article>
</journal></catalog>

相关文章:

  • aspx页面导出为word
  • mysql优化之索引优化
  • 使用SAX解析XML
  • AJAX实现类Google Suggest效果
  • Android:百度地图 + 百度导航
  • 文章太长了!~关于 XML 的一些基础知识
  • iOS: FFmpeg的使用一
  • ??如何把JavaScript脚本中的参数传到java代码段中
  • HD1285(拓扑排序)
  • 如何用javascript设置延时执行
  • 设计模式--3.模板方法模式
  • 实现JSP数据和JavaScript数据交互使用
  • 使用Apache Xerces解析XML文档
  • 禁ping以及清理系统多余账号说明
  • 使用dom4j和XPath解析XML之例子二
  • [原]深入对比数据科学工具箱:Python和R 非结构化数据的结构化
  • JAVA SE 6 GC调优笔记
  • October CMS - 快速入门 9 Images And Galleries
  • Python 基础起步 (十) 什么叫函数?
  • Python利用正则抓取网页内容保存到本地
  • springMvc学习笔记(2)
  • uva 10370 Above Average
  • vue学习系列(二)vue-cli
  • 阿里云应用高可用服务公测发布
  • 翻译 | 老司机带你秒懂内存管理 - 第一部(共三部)
  • 基于Dubbo+ZooKeeper的分布式服务的实现
  • ​决定德拉瓦州地区版图的关键历史事件
  • #Linux(权限管理)
  • #数学建模# 线性规划问题的Matlab求解
  • (6)STL算法之转换
  • (9)YOLO-Pose:使用对象关键点相似性损失增强多人姿态估计的增强版YOLO
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (poj1.2.1)1970(筛选法模拟)
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (附源码)php投票系统 毕业设计 121500
  • (算法)N皇后问题
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决
  • (转)ORM
  • (转)甲方乙方——赵民谈找工作
  • (转载)VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)
  • .equal()和==的区别 怎样判断字符串为空问题: Illegal invoke-super to void nio.file.AccessDeniedException
  • .net core IResultFilter 的 OnResultExecuted和OnResultExecuting的区别
  • .net core 连接数据库,通过数据库生成Modell
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .NET Framework .NET Core与 .NET 的区别
  • .net 按比例显示图片的缩略图
  • .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
  • .NET中的十进制浮点类型,徐汇区网站设计
  • /usr/bin/perl:bad interpreter:No such file or directory 的解决办法
  • @Builder用法
  • @RestController注解的使用
  • @RunWith注解作用
  • @我的前任是个极品 微博分析
  • [].shift.call( arguments ) 和 [].slice.call( arguments )