java对xml文件操作的工具类

首先列出目录结构及其文件内的功能:

com.testxml

          .main    //所有对象的入口,测试类
          .books   //实体
          .boos.xml   //xml文件
          .booksDao      //将实体中的值转化为xml文件,保存到制定目录下的xml文件中
                         //解析xml文件转化为list<实体>
          .testxml  //未整合的对xml文件的操作
          .xmlUtil       //xml工具类,创建document对象
                         //得到父节点的子节点的值,只限于父节点下面的子节点是末端元素
                         //将document对象写入到指定的xml文件中去

                         //删除指定节点及其子节点

xml工具类代码:

package com.testxml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class xmlUtil {

	/**
	 * 创建document对象
	 * @param 相对路径
	 * @return
	 * @throws Exception
	 */
	public  static Document getDocument(String str) throws Exception
	{
		//获取dom解析器工厂
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		//获取具体的解析器
		DocumentBuilder db = dbf.newDocumentBuilder();
		//解析xml文件,获取document对象
		Document document = db.parse(new File(str));
		return document;
	}
	
	/**
	 * 得到父节点的子节点的值,只限于父节点下面的子节点是末端元素
	 * @param document   xml对象
	 * @param parentSrt  父元素
	 * @param childStr   子元素
	 * @param i   第几个父元素,从0开始
	 * @return
	 */
	public  static String getChildValue(Document document,String parentSrt,String childStr,int i)
	{
		NodeList list = document.getElementsByTagName(parentSrt);
	    Element element = (Element) list.item(i);
	    if(element==null)
	    {
	    	throw new NullPointerException("指定的父节点不存在");
	    }
	    String content = element.getElementsByTagName(childStr).item(0).getFirstChild().getNodeValue();
		return content;
	}
	
	/**
	 * 将document对象写入到指定的xml文件中去
	 * @param document
	 * @param str  xml所在目录
	 * @throws Exception
	 */
	 public  static void saveDocument(Document document,String str) throws Exception
	 {
	    TransformerFactory transformerFactory = TransformerFactory.newInstance();  
        //step10:获得一个Transformer对象  
        Transformer transformer = transformerFactory.newTransformer();  
        //step11:把document对象用一个DOMSource对象包装起来  
        Source xmlSource = new DOMSource(document);  
        //step12:建立一个存储目标对象  
        Result outputTarget = new StreamResult(new File(str));  
        //step13:生成相应的xml文件  
        transformer.setOutputProperty("encoding", "UTF-8");
        transformer.transform(xmlSource, outputTarget);  
	 }
	
	 /**
	  * 删除指定节点及其子节点
	  * @param name  节点键
	  * @param str   xml文件所在目录
	  * @return
	  * @throws Exception
	  */
	 public  static boolean delete(Document document,String name,String str) throws Exception
	 {
		 boolean result = false; 
		 NodeList nodeLists = document.getElementsByTagName(name); 
		 int len=nodeLists.getLength();
		 //遍历这个nodelist,每次都删除nodelist的第一个,因为nodelist的size是不断变化的
		 for(int i=0;i<len;i++)
		 { 
			 nodeLists.item(0).getParentNode().removeChild(nodeLists.item(0)); 
		 }
		 xmlUtil.saveDocument(document, str);
		 result=true;
		 return result;
	 }
	 
	public static void main(String[] args) throws Exception {
		Document document=xmlUtil.getDocument("./src/testxml/books.xml");
		String value=xmlUtil.getChildValue(document,"book","title",1);
		System.out.println(value);
	}

}


booksdao类代码:

package com.testxml;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class booksDao {

	private Document document;
	public booksDao(String str) throws Exception
	{
		if(document==null)
		{
			document = xmlUtil.getDocument(str);
		}
	}
	
	/**
	 * 将实体中的值转化为xml文件,保存到制定目录下的xml文件中
	 * @param books  实体
	 * @param str  存放xml文件的路径
	 * @return  是否保存成功
	 * @throws Exception
	 */
	 public boolean save(books books,String str) throws Exception
	 {  
		 if(books==null)
		 {
			 throw new IllegalArgumentException("实体类book不能为null");  
		 }
		 boolean result = false; 
		 
		 Element book = document.createElement("book"); 
		 //给获取的book元素添加属性
		 book.setAttribute("category", books.getCategory());  
		 //创建元素,添加到book上面
		 Element title = document.createElement("title");  
		 title.setTextContent(books.getTitle()); 
		 book.appendChild(title);
		 Element author = document.createElement("author");  
		 author.setTextContent(books.getAuthor());
		 book.appendChild(author);
		 
		 //获取根节点,根节点添加book元素
		 Node tempNode=document.getElementsByTagName("booklist").item(0);
		 tempNode.appendChild(book);
		 
		 xmlUtil.saveDocument(document, str);
		 result=true;
		 return result;
	 }
	 
	 /**
	  * 删除指定节点及其子节点
	  * @param name  节点键
	  * @param str   xml文件所在目录
	  * @return
	  * @throws Exception
	  */
	 public void delete(String name,String str) throws Exception
	 {
		 boolean result=xmlUtil.delete(document, name, str);
		 if(result==true)
		 {
			 System.out.println("删除成功!");
		 }
	 }
	 
	 /**
	  * 解析xml文件转化为list<实体>
	  * @param name
	  * @return
	  */
	 public List<books> GetEntityList(String name)
	 {
		 List<books> booklists=new ArrayList<books>();
		 NodeList nodeLists = document.getElementsByTagName(name);
		 for(int i=0;i<nodeLists.getLength();i++)
		 {  
             Element e = (Element) nodeLists.item(i); 
             books books=new books();
             books.setCategory(e.getAttribute("category"));
             books.setTitle(e.getElementsByTagName("title").item(0).getTextContent());
             books.setAuthor(e.getElementsByTagName("author").item(0).getTextContent());
             booklists.add(books);
		 }  
		 return booklists;
	 }
	
}

books.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<booklist>
	<book category="这是分类1">
		<title>这是标题1</title>
		<author>这是作者1</author>
	</book>
	<book category="这是分类2">
		<title>这是标题2</title>
		<author>这是作者2</author>
	</book>
	<book category="这是分类3">
		<title>这是标题3</title>
		<author>这是作者3</author>
	</book>
	<book category="这是分类4">
		<title>这是标题4</title>
		<author>这是作者4</author>
	</book>
</booklist>
其他文件代码略。


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析的XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值