这个也是自己转载的,现在对DOM还比较熟悉,自己不要只是复制代码,可以试着去熟悉其中的一两种,以后会有用处的。
xml的四种解析方法及源代码(SAX、DOM、JDOM、DOM4J)
第一种:SAX解析
SAX处理机制:SAX是一种基于事件驱动的API。利用SAX解析XML文档,牵涉到两个部分:解析器和事件处理器。解析器负责读取XML文档,并向事件处理器发生事件,如元素开始和元素结束事件;而事件处理器则负责对事件做出响应,对传递的XML数据进行处理。
测试用的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>
<?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
Xml代码
- <!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>
- <!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解析实例一
org.xml.sax.DefalutHandler类: 可以扩展该类,给出自己的解析实现
SAXPrinter.java
Java代码
- 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();
- }
- }
- }
- 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解析实例二
org.xml.sax.ContentHandler接口: 通过实现该接口给出自己的解析实现。
org.xml.sax.ErrorHandler接口:如果SAX应用程序需要实现定制的错误处理,那么它必须实现这个接口,并调用XMLReader对象的setErrorHandler()方法向解析器注册异常处理实例,这样,解析器将通过这个接口报告所有的错误和警告。
ContentHandlerImpl.java
Java代码
- 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
- {
- }
- }
- 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
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();
- }
- 1. }
- 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
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());
- }
- }
- }
- 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解析
DOM中的核心概念就是节点。DOM在分析XML文档时,将将组成XML文档的各个部分(元素、属性、文本、注释、处理指令等)映射为一个对象(节点)。在内存中,这些节点形成一课文档树。整棵树是一个节点,树中的每一个节点也是一棵树(子树),可以说,DOM就是对这棵树的一个对象描述,我们通过访问树中的节点来存取XML文档的内容。
PS:属性节点是附属于元素的,不能被看做是元素的子节点,更不能作为一个单独的节点
DOMPrinter.java
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()+"\"");
- }
- }
- }
- 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
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();
- }
- }
- }
- 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解析
JDOM利用了java语言的优秀特性,极大地简化了对XML文档的处理,相比DOM简单易用。JDOM也使用对象树来表示XML文档,JDOM使用SAXj解析器来分析XML文档,构建JDOM树。然而JOMD本身并没有提供解析器,它使用其他开发商提供的标准SAX解析器,JDOM默认通过JAXP来选择解析器,可以通过手动知道解析器的类名来设置。
首先要在工程中添加jdom的jar包,这里使用jdom1.0.jar。(见附件)
JDOMConvert.java
- 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();
- }
- }
- }
- 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
- <span style="color:#000000;">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();
- }
- }
- }
- 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();
- }
- }
- }
- </span>
第四种:DOM4J解析
dom4j与JDOM一样,也是一种用于解析XML文档的开放源代码的XML框架,dom4j也应用于java平台,dom4j API使用了java集合框架并完全支持DOM、SAX和JAXP。与JDOM不同的是,dom4j使用接口和抽象类,虽然dom4j的API相对复杂些,但它提供了比JDOM更好的灵活性。dom4j也使用SAX解析器来分析XML文档,创建dom4j树。此外dom4j也可以接收DOM格式的内容,并提供了从dom4j树到SAX事件流或W3C DOM树的输出机制。与JDOM不同,dom4j自带了一个SAX解析器Aelfred2,如果没有显示的设置SAX解析器,也没有通过系统属性org.xml.sax.driver设置解析器,dom3j将会使用JAXP来加载JAXP配置的解析器,如果创建解析器失败,那么最后才使用dom4j自带的Aelfred2解析器。
同样,首先要在工程中添加dom4j的jar包,这里使用dom4j-1.6.1.jar。(见附件)
Dom4j生成XML文档db.xml:Dom4jCreate.java
Java代码
- 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();
- }
- }
- }
- 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();
- }
- }