Java操作XML对象

--org.w3c.dom对象---------------------------

(1)org.w3c.dom W3C推荐的用于XML标准规划文档对象模型的接口;
(2)org.xml.sax  用于对XML进行语法分析的事件驱动的XML简单API(SAX);
(3)Javax.xml.parsers     解析器工厂工具,程序员获得并配置特殊的特殊语法分析器。

 package com.primeton.eos.arp.report; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.primeton.tp.core.api.BizContext; /** * @author hujing * @version 1.0 * @date 2009-12-8 * @class_displayName DomReader */ public class DomReader { public DocumentBuilder builder; private Document doc; /** * 构造器 * * @throws Exception */ public DomReader() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); this.builder = dbf.newDocumentBuilder(); this.doc = builder.newDocument(); } /** * 解析xml字符串 * * @param xmlstr * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public DomReader(String xmlstr) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(xmlstr); InputSource is = new InputSource(sr); this.doc = db.parse(is); } /** * 解析xml文件 * * @param file * @throws Exception */ public DomReader(File file) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); this.doc = db.parse(file); } /** * 取节点值 * * @param tagname * @return List */ public List getNodeValues(String tagname) { List arr = new ArrayList(); doc.normalize(); NodeList list = doc.getElementsByTagName(tagname); for (int i = 0; i < list.getLength(); i++) { if (list.item(i).getFirstChild() != null) { arr.add(list.item(i).getFirstChild().getNodeValue()); } } return arr; } /** * 重命名节点名 * @param oldChild * @param newName * @throws Exception */ public void renameNodeName(Node oldChild,String newName) throws Exception { Node parent = oldChild.getParentNode(); Element newChild = doc.createElement(newName); // 是否有子节点 if (oldChild.hasChildNodes()) { NodeList temp = oldChild.getChildNodes(); for (int i = 0; i < temp.getLength(); i++) { newChild.appendChild(temp.item(i)); i--; } } // 是否有属性 if (oldChild.hasAttributes()) { NamedNodeMap map = oldChild.getAttributes(); Node tn = null; for (int j = 0; j < map.getLength(); j++) { tn = map.item(j); newChild.setAttribute(tn.getNodeName(), tn.getNodeValue()); } } parent.replaceChild(newChild, oldChild); } }   

 

你可能感兴趣的:(java,xml,exception,String,list,File)