精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-04-11
最后修改:2009-04-14
xml的四种解析方法及源代码(SAX、DOM、JDOM、DOM4J) 第一种:SAX解析 测试用的xml文件:db.xml <?xml version="1.0" encoding="UTF-8"?> <!--<!DOCTYPE dbconfig SYSTEM "db.dtd">--> <dbconfig> <db type="oracle"> <driver>oracle.jdbc.driver.OracleDriver</driver> <url>jdbc:oracle:thin:@localhost:1521:oracle</url> <user>scott</user> <password>tiger</password> </db> </dbconfig> DTD文件db.dtd <!ELEMENT dbconfig (db+)> <!ELEMENT db (driver,url,user,password)> <!ELEMENT driver (#PCDATA)> <!ELEMENT url (#PCDATA)> <!ELEMENT user (#PCDATA)> <!ELEMENT password (#PCDATA)> <!ATTLIST db type CDATA #REQUIRED> SAX解析实例一 import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXPrinter extends DefaultHandler { /** *//** * 文档开始事件 */ public void startDocument() throws SAXException { System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); } /** *//** * 接收处理指令事件 */ public void processingInstruction(String target, String data) throws SAXException { System.out.println("<?"+target+" "+data+"?>"); } /** *//** * 元素开始事件 * 参数说明: * uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。 * localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。 * qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。 * attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。 */ public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { System.out.print("<"+qName);//输出元素名称 int len=attrs.getLength();//元素属性列表长度 //利用循环输出属性列表 for(int i=0;i<len;i++) { System.out.print(" "); System.out.print(attrs.getQName(i)); System.out.print("=\""); System.out.print(attrs.getValue(i)); System.out.print("\""); } System.out.print(">"); } /** *//** * 元素中字符数据事件:接收元素中字符数据 * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外) * 2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器 */ public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch,start,length)); } /** *//** * 结束元素事件 */ public void endElement(String uri, String localName, String qName) throws SAXException { System.out.print("</"+qName+">"); } public static void main(String[] args) { SAXParserFactory spf=SAXParserFactory.newInstance(); try { SAXParser sp=spf.newSAXParser(); sp.parse(new File("db.xml"),new SAXPrinter()); } catch (Exception e) { e.printStackTrace(); } } } SAX解析实例二 import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class ContentHandlerImpl implements ContentHandler { /** *//** * 文档开始事件 */ public void startDocument() throws SAXException { System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); } /** *//** * 接收处理指令事件 */ public void processingInstruction(String target, String data) throws SAXException { System.out.println("<?"+target+" "+data+"?>"); } /** *//** * 元素开始事件 * 参数说明: * uri - 名称空间 URI,如果元素没有任何名称空间 URI,或者没有正在执行名称空间处理,则为空字符串。 * localName - 本地名称(不带前缀),如果没有正在执行名称空间处理,则为空字符串。 * qName - 限定的名称(带有前缀),如果限定的名称不可用,则为空字符串。 * attributes - 附加到元素的属性。如果没有属性,则它将是空的 Attributes 对象。 */ public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { System.out.print("<"+qName);//输出元素名称 int len=attrs.getLength();//元素属性列表长度 //利用循环输出属性列表 for(int i=0;i<len;i++) { System.out.print(" "); System.out.print(attrs.getQName(i)); System.out.print("=\""); System.out.print(attrs.getValue(i)); System.out.print("\""); } System.out.print(">"); } /** *//** * 元素中字符数据事件:接收元素中字符数据 * 注意:1.应用程序不要试图读取ch数组指定范围外的数据,(即start至length之外) * 2.有些解析器将使用ignorableWhitespace()方法来报告元素内容中的空白,而不是characters()方法,如:进行有效性验证的解析器 */ public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch,start,length)); } /** *//** * 结束元素事件 */ public void endElement(String uri, String localName, String qName) throws SAXException { System.out.print("</"+qName+">"); } public void endDocument() throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void setDocumentLocator(Locator locator) { } public void skippedEntity(String name) throws SAXException { } public void startPrefixMapping(String prefix, String uri) throws SAXException { } } ErrorHandlerImpl.java public class ErrorHandlerImpl implements ErrorHandler { public void warning(SAXParseException e) throws SAXException { System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage()); } public void error(SAXParseException e) throws SAXException { System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage()); } public void fatalError(SAXParseException e) throws SAXException { System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage()); } private String getLocationString(SAXParseException e) { StringBuffer sb=new StringBuffer(); String publicId=e.getPublicId(); if(publicId!=null) { sb.append(publicId); sb.append(" "); } String systemId=e.getSystemId(); if(systemId!=null) { sb.append(systemId); sb.append(" "); } sb.append(e.getLineNumber()); sb.append(":"); sb.append(e.getColumnNumber()); return sb.toString(); } } SaxParserTest.java import java.io.FileInputStream; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class SaxParserTest { public static void main(String[] args) { try { XMLReader xmlReader=XMLReaderFactory.createXMLReader(); //关闭或打开验证 xmlReader.setFeature("http://xml.org/sax/features/validation",true); //注册事件处理器 xmlReader.setContentHandler(new ContentHandlerImpl()); //注册异常处理器 xmlReader.setErrorHandler(new ErrorHandlerImpl()); xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml"))); } catch (Exception e) { System.out.println(e.getMessage()); } } } 第二种:DOM解析 DOMPrinter.java import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.sun.org.apache.xerces.internal.parsers.DOMParser; public class DOMPrinter { public static void main(String[] args) { try { /** *//** 获取Document对象 */ DOMParser parser = new DOMParser(); parser.parse("db.xml"); Document document = parser.getDocument(); printNode(document); } catch (Exception e) { e.printStackTrace(); } } public static void printNode(Node node) { short nodeType=node.getNodeType(); switch(nodeType) { case Node.PROCESSING_INSTRUCTION_NODE://预处理指令类型 printNodeInfo(node); break; case Node.ELEMENT_NODE://元素节点类型 printNodeInfo(node); printAttribute(node); break; case Node.TEXT_NODE://文本节点类型 printNodeInfo(node); break; default: break; } Node child=node.getFirstChild(); while(child!=null) { printNode(child); child=child.getNextSibling(); } } /** *//** * 根据节点类型打印节点 * @param node */ public static void printNodeInfo(Node node) { if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println("NodeName: " + node.getNodeName()); } else if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue().trim(); if (!value.equals("")) System.out.println("NodeValue: " + value); else System.out.println(); }else { System.out.println(node.getNodeName()+" : "+node.getNodeValue()); } } /** *//** * 打印节点属性 * @param aNode 节点 */ public static void printAttribute(Node aNode) { NamedNodeMap attrs = aNode.getAttributes(); if(attrs!=null) { for (int i = 0; i < attrs.getLength(); i++) { Node attNode = attrs.item(i); System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\""); } } } DOM生成XML文档:DOMCreateExample.java import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; public class DOMCreateExample { public static void main(String[] args) throws ParserConfigurationException { //DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation(); DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFact.newDocumentBuilder(); Document doc = builder.newDocument(); //Document doc = domImp.createDocument(null, null, null); Element root = doc.createElement("games"); Element child1 = doc.createElement("game"); child1.appendChild(doc.createTextNode("Final Fantasy VII")); child1.setAttribute("genre", "rpg"); root.appendChild(child1); doc.appendChild(root); XMLSerializer serial; try { serial = new XMLSerializer(new FileOutputStream("domcreate.xml"), null); serial.serialize(doc); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 第三种JDOM解析 import java.io.File; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class JDOMConvert { public static void main(String[] args) { SAXBuilder saxBuilder=new SAXBuilder(); try { Document doc=saxBuilder.build(new File("domdb.xml")); //首先创建好节点 Element eltDb=new Element("db"); Element eltDriver=new Element("driver"); Element eltUrl=new Element("url"); Element eltUser=new Element("user"); Element eltPassword=new Element("password"); //设置节点的值 eltDriver.setText("com.mysql.jdbc.Driver"); eltUrl.setText("jdbc:mysql://localhost/mySql"); eltUser.setText("root"); eltPassword.setText("xlc"); //添加到根节点 eltDb.addContent(eltDriver); eltDb.addContent(eltUrl); eltDb.addContent(eltUser); eltDb.addContent(eltPassword); //根节点设置属性 eltDb.setAttribute("type","mysql"); Element root=doc.getRootElement(); //root.removeChild("db");//删除节点 root.addContent(eltDb);//增加节点 //修改db节点中内容 root.getChild("db").getChild("user").setText("system"); root.getChild("db").getChild("password").setText("manager"); XMLOutputter xmlOut=new XMLOutputter(); //设置XML格式 Format fmt=Format.getPrettyFormat(); fmt.setIndent(" "); fmt.setEncoding("utf-8"); xmlOut.setFormat(fmt); xmlOut.output(doc,System.out); } catch (Exception e) { e.printStackTrace(); } } } JDOM生成XML文档:JDOMCreate.java import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; public class JDOMCreate { public static void main(String[] args) { Document doc = new Document(new Element("games")); Element newGame = new Element("game").setText("Final Fantasy VI"); doc.getRootElement().addContent(newGame); newGame.setAttribute("genre", "rpg"); XMLOutputter domstream = new XMLOutputter(); try { domstream.output(doc, System.out); } catch (IOException e) { e.printStackTrace(); } } } 第四种:DOM4J解析 import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class Dom4jCreate { public static void main(String[] args) { Document doc = DocumentHelper.createDocument(); doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl' href='db.xsl'"); doc.addDocType("dbconfig", null,"db.dtd"); //Element root=DocumentHelper.createElement("dbconfig"); // doc.setRootElement(root); Element root = doc.addElement("dbconfig"); Element eltDb= root.addElement("db"); Element eltDriver = eltDb.addElement("driver"); Element eltUrl = eltDb.addElement("url"); Element eltUser = eltDb.addElement("user"); Element eltPassword = eltDb.addElement("password"); eltDriver.setText("com.mysql.jdbc.Driver"); eltUrl.setText("jdbc:mysql://localhost/mySql"); eltUser.setText("root"); eltPassword.setText("xlc"); eltDb.addAttribute("type","mysql"); try { //设置输出格式 OutputFormat outFmt = new OutputFormat(" ", true); outFmt.setEncoding("UTF-8"); /**//*PrintWriter pw = new PrintWriter(System.out); doc.write(pw); pw.flush(); pw.close();*/ XMLWriter xmlWriter = new XMLWriter(System.out, outFmt); // XMLWriter xmlWriter=new XMLWriter(new FileWriter("db.xml"),outFmt); xmlWriter.write(doc); xmlWriter.flush(); xmlWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } Dom4j修改XML文档db.xml:Dom4jModify.java import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jModify { public Document modifyDocument(File inputXml) { try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); document.addDocType("dbconfig",null,"db.dtd"); List list = document.content(); // Iterator iter = document.nodeIterator(); Iterator iter = list.iterator(); Element element = (Element) iter.next(); element.element("db").attribute("type").setValue("mysql"); element.element("db").element("url").setText("jdbc:mysql://localhost/mySql"); element.element("db").element("driver").setText("com.mysql.jdbc.Driver"); element.element("db").element("user").setText("root"); element.element("db").element("password").setText("xlc"); // 设置输出格式 OutputFormat outFmt = new OutputFormat(" ", true); outFmt.setEncoding("UTF-8"); XMLWriter xmlWriter=new XMLWriter(new FileWriter("domdb-modified.xml"),outFmt); xmlWriter.write(document); xmlWriter.flush(); xmlWriter.close(); return document; } catch (Exception e) { System.out.println(e.getMessage()); return null; } } public static void main(String[] args) throws Exception { Dom4jModify dom4jParser = new Dom4jModify(); Document document = dom4jParser.modifyDocument(new File("domdb.xml")); OutputFormat outFmt = new OutputFormat(" ", true); outFmt.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(System.out,outFmt); xmlWriter.write(document); xmlWriter.flush(); xmlWriter.close(); } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 10585 次