编程用JAVA解析XML的方式 —动力节点
第二十二课使用Java解析XML.
JDom解析器 JDOM要求您设置底层的解析器,JDOM本 身不进行验证。就是说,如果JDOM能够完 成您所需要的所有功能,而且速度满足您 的需要,它可以简化您的编码工作。
内容总结 理解DOM,SAX解析XML原理 了解DOM,SAX解析的优缺点 使用DOM,SAX解析XML文档 使用DOM4J,JDOM解析XML文档
独立实践
写一个XML文档:包括JDBC连接所需要的驱动, url,用户名,密码等 使用SAX或者DOM解析上面的XML建立数据库的 连接 使用DOM4J解析一个判断用户的登陆的操作,用 户信息存在XML文档里 使用JDOM解析上一章的一个关于学生课程信息 的XML文档,并在控制台显示数据 使用任何一种解析方式对学生课程信息的XML文 档进行写一行增加课程信息的数据。
Dom与Sax解析器的对比
一般来说以下情况应使用DOM解析器:
需要详细了解文档的结构 需要改变文档的结构(也许您需要对元素排序,增加 新的元素等等) 需要多次引用解析的信息
进一步推广,在以下情况中应使用SAX解析器:
内存少 只需要XML文档中少量元素或属性 解析的信息只使用一次
Dom解析器
当你使用DOM解析器解析一个XML文档时,您得到一棵 结构树,它表示XML文档的内容。所有的文本,元素和属 性,都在这个树结构中.解析的过程如下图:
Dom解析器
DOM以及广义的基于树的处理具有几个优点 首先,由于树在内存中是持久的,因此可以修改它以便应 用程序能对数据和结构作出更改。它还可以在任何时候在 树中上下导航,而不是像SAX那样是一次性的处理。 DOM使用起来也要简单得多。 另一方面,在内存中构造这样的树涉及大量的开销。大型 文件完全占用系统内存容量的情况并不鲜见。此外,创建 一棵DOM树可能是一个缓慢的过程。为了满足该缺点, 我们使用SAX(Simple API for XML)API处理XML文档 内容。它的设计目标是占用更少的内存,把更多的工作交 给程序员。SAX和DOM是互补的,有各自的适用环境。
java xml注解解析
java xml注解解析摘要:1.简介:Java XML注解的作用和应用场景2.XML注解的基本语法3.常用Java XML注解规范4.实战案例:Java XML注解在项目中的应用5.总结:Java XML注解的优势和局限性正文:【简介】Java XML注解是Java语言中一种用于描述XML文档结构的注解方式。
通过使用XML注解,开发人员可以在代码中更方便地处理和解析XML数据。
在实际项目中,Java XML注解广泛应用于数据传输、配置文件、数据持久化等方面。
【XML注解的基本语法】XML注解使用XML语法进行编写,通常包括以下几个部分:1.开始标签:用于定义注解的起始位置。
2.属性:用于为注解添加额外的信息,如数据类型、默认值等。
3.结束标签:用于表示注解的结束位置。
例如,以下是一个简单的Java XML注解示例:```xml<annotation type="ng.String"><attribute name="value" default="default_value" /> </annotation>```【常用Java XML注解规范】Java XML注解有以下几个常用规范:1.@XmlRootElement:指定XML元素的名称。
2.@XmlAttribute:指定XML属性的名称和类型。
3.@XmlElement:指定XML元素的名称和类型。
4.@XmlValue:指定XML元素的值。
5.@XmlSeeAlso:指定与当前注解相关的其他注解。
以下是一个使用上述规范的Java XML注解示例:```java@XmlRootElement(name = "person")public class Person {@XmlAttribute(name = "name", required = true)private String name;@XmlAttribute(name = "age", defaultValue = "0")private int age;@XmlElement(name = "address")private Address address;// 省略getter和setter方法}public class Address {@XmlValueprivate String street;// 省略getter和setter方法}```【实战案例】在实际项目中,Java XML注解可以提高代码的可读性和可维护性。
java解析XML的4种方法
选择DOM还是选择SAX? 对于需要自己编写代码来处理XML文档的开发人员来说, 选择DOM还是SAX 解析模型是一个非常重要的设计 决策。 DOM采用建立树形结构的方式访问XML文档,而SAX采用的事件模型。
DOM解析器把XML文档转化为一个包含其内容的树,并可以对树进行遍历。用DOM解析模型的优点是编程容易,开发人员只需要调用建树的指令,然后利用 navigation APIs访问所需的树节点来完成任务。可以很容易的添加和修改树中的元素。然而由于使用 DOM解析器的时候需要处理整个XML文档,所以对性能和内存的要求比较高,尤其是遇到很大的XML文件的时候。由于它的遍历能力,DOM解析器常用于 XML文档需要频繁的改变的服务中。
String tag = (String) tags.peek();
try{
File f=new File("data_10k.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
System.out.println(" 车主地址:" +
doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
为支持所有这些功能,DOM4J使用接口和抽象基本类方法。 DOM4J大量使用了API中的Collections类,但是在许多情况下,它还提供一些替代方法以允许更好的性能或更直接的编码方法。直接好处是,虽然DOM4J付出了更复杂的API的代价,但是它提供了比JDOM大得多的灵活性。
Java动态生成和解析xml文件步骤详解
Java动态⽣成和解析xml⽂件步骤详解⾸先声明,这个地⽅是利⽤dom4j进⾏解析和⽣成,需要⽤到dom4j的jar包,所以⾸先需要我们获取jar包:<dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency>⽣成xml⽂件代码案列:package day12;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;/*** 写出XML⽂档*/public class WriteXmlDemo {public static void main(String[] args) {List<Emp> empList = new ArrayList<Emp>();empList.add(new Emp(1,"张三",22,"男",3000));empList.add(new Emp(2,"李四",23,"⼥",4000));empList.add(new Emp(3,"王五",24,"男",5000));empList.add(new Emp(4,"赵六",25,"⼥",6000));empList.add(new Emp(5,"钱七",26,"男",7000));empList.add(new Emp(6,"传奇",21,"男",8000));/** 写出XML⽂档的⼤致步骤* 1.创建空⽩⽂档对象Document* 2.向该⽂档中添加根元素* 3.按照规定的XML⽂档结构从根元素开始,逐级添加⼦元素,已完成该结构* 4.创建XMLWriter* 5.将Document对象写出成XML⽂档* 6.将XMLWriter关闭*///1Document doc = DocumentHelper.createDocument();/** 2.Element addElement(String name)* Document提供的该⽅法是⽤来向当前⽂档中添加给定名字的根元素。
java 解析xml方法
java 解析xml方法在Java中,有许多库可以用于解析XML文档。
其中,DOM和SAX 是最常用的两种。
DOM是一种基于树结构的解析方式,而SAX是一种基于事件的解析方式。
1.DOM解析XMLDOM解析器将整个XML文档读入内存,并将其转换为一个树形结构。
这个树形结构可以使用Document Object Model (DOM) API来访问。
DOM解析器可以很容易地遍历这个树形结构,并提取出需要的元素和属性。
下面是一个使用DOM解析器读取XML文件的示例:```javaDocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(newFile('example.xml'));Element root = document.getDocumentElement();NodeList nodeList = root.getElementsByTagName('book'); for (int i = 0; i < nodeList.getLength(); i++) {Node node = nodeList.item(i);if (node.getNodeType() == Node.ELEMENT_NODE) {Element element = (Element) node;String title =element.getElementsByTagName('title').item(0).getTextConten t();String author =element.getElementsByTagName('author').item(0).getTextConte nt();System.out.println('Title: ' + title + ', Author: ' + author);}}```在这个例子中,我们使用了DocumentBuilderFactory和DocumentBuilder类来创建一个DOM解析器。
Java中对XML的解析详解
Java中对XML的解析详解个⼈理解类似.net的XmlDocument,解析的时候效率不⾼,占⽤内存,不适合⼤XML的解析;基于事件的解析,当解析到xml的某个部分的时候,会触发特定事件,可以在⾃定义的解析类中定义当事件触发时要做得事情;个⼈感觉⼀种很另类的⽅式,不知道.Net体系下是否有没有类似的⽅式?个⼈理解类似.net的XmlReader⽅式,效率⾼,占⽤内存少,适⽤⼤XML的解析;不过SAX⽅式之前也⽤过,本⽂主要介绍JAXB,这⾥只贴下主要代码:复制代码代码如下:import java.util.ArrayList;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class ConfigParser extends DefaultHandler {private String currentConfigSection;public SysConfigItem sysConfig;public List<InterfaceConfigItem> interfaceConfigList;public List<FtpConfigItem> ftpConfigList;public List<AdapterConfigItem> adapterConfigList;public void startDocument() throws SAXException {sysConfig = new SysConfigItem();interfaceConfigList = new ArrayList<InterfaceConfigItem>();ftpConfigList = new ArrayList<FtpConfigItem>();adapterConfigList = new ArrayList<AdapterConfigItem>();}public void endDocument() throws SAXException {}public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {if (qName.equalsIgnoreCase("Item") && attributes.getLength() > 0) {if (currentConfigSection.equalsIgnoreCase("SysConfigItem")) {sysConfig = new SysConfigItem(attributes);} else if (currentConfigSection.equalsIgnoreCase("InterfaceConfigItems")) {interfaceConfigList.add(new InterfaceConfigItem(attributes));} else if (currentConfigSection.equalsIgnoreCase("FtpConfigItems")) {ftpConfigList.add(new FtpConfigItem(attributes));} else if (currentConfigSection.equalsIgnoreCase("AdapterConfigItems")) {adapterConfigList.add(new AdapterConfigItem(attributes));}} else {currentConfigSection = qName;}}public void endElement(String uri, String localName, String qName) throws SAXException {}public void characters(char ch[], int start, int length) throws SAXException {}}复制代码代码如下:import ng.reflect.Field;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import org.xml.sax.Attributes;public class ConfigItemBase {private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public ConfigItemBase() {}/*** ⽬前只⽀持⼏种常⽤类型如果需要⽀持其他类型,请修改这⾥的代码** @param attributes*/public ConfigItemBase(Attributes attributes) {Class<?> cls = this.getClass();Field[] fields = cls.getDeclaredFields();for (Field field : fields) {String fieldType = field.getType().getSimpleName();for (int i = 0; i < attributes.getLength(); i++) {if (attributes.getQName(i).equalsIgnoreCase(field.getName())) {field.setAccessible(true);try {if (fieldType.equalsIgnoreCase("String")) {field.set(this, attributes.getValue(attributes.getQName(i)));} else if (fieldType.equalsIgnoreCase("Integer")) {field.set(this, Integer.valueOf(attributes.getValue(attributes.getQName(i))));} else if (fieldType.equalsIgnoreCase("Double")) {field.set(this, Double.valueOf(attributes.getValue(attributes.getQName(i))));} else if (fieldType.equalsIgnoreCase("Date")) {field.set(this, GetDate(attributes.getValue(attributes.getQName(i))));} else {System.out.println("Warning:Unhandler Field(" + field.getName() + "-" + fieldType + ")");}} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}break;}}}}public String toString() {String result = "";Class<?> cls = this.getClass();String classNameString = cls.getName();result += classNameString.substring(stIndexOf('.') + 1, classNameString.length()) + ":"; Field[] fields = cls.getDeclaredFields();for (Field field : fields) {try {result += field.getName() + "=" + field.get(this) + ";";} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return result;}/*** 处理时间类型属性(时间格式要求为:yyyy-MM-dd hh:mm:ss)** @param dateString* @return*/private static Date GetDate(String dateString) {Date date = null;try {date = dateFormat.parse(dateString);} catch (ParseException e) {e.printStackTrace();}return date;}}JAXB(Java Architecture for XML Binding)这⾥⽤⽐较复杂的移动BatchSyncOrderRelationReq接⼝XML做为⽰例(感觉能解这个⼤家基本上够⽤了),报⽂格式如下(SvcCont⾥的CDATA内容是报⽂体,太恶⼼了):复制代码代码如下:<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><InterBOSS><Version>0100</Version><TestFlag>0</TestFlag><BIPType><BIPCode>BIP2B518</BIPCode><ActivityCode>T2101518</ActivityCode><ActionCode>0</ActionCode></BIPType><RoutingInfo><OrigDomain>BOSS</OrigDomain><RouteType>routeType</RouteType><Routing><HomeDomain>XXXX</HomeDomain><RouteValue>routeValue</RouteValue></Routing></RoutingInfo><TransInfo><SessionID>2013041017222313925676</SessionID><TransIDO>2013041017222313925676</TransIDO><TransIDOTime>20130410172223</TransIDOTime><TransIDH></TransIDH><TransIDHTime></TransIDHTime></TransInfo><SNReserve><TransIDC></TransIDC><ConvID></ConvID><CutOffDay></CutOffDay><OSNTime></OSNTime><OSNDUNS></OSNDUNS><HSNDUNS></HSNDUNS><MsgSender></MsgSender><MsgReceiver></MsgReceiver><Priority></Priority><ServiceLevel></ServiceLevel><SvcContType></SvcContType></SNReserve><Response><RspType>rspType</RspType><RspCode>rspCode</RspCode><RspDesc>rspDesc</RspDesc></Response><SvcCont><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <batchSyncOrderRelationReq><msgTransactionID>210001BIP2B518130410172223651627</msgTransactionID> <reqNum>2</reqNum><reqBody><oprNumb>210001BIP2B518130410172224341871</oprNumb><subscriptionInfo><oprTime>oprTime1</oprTime><actionID>actionId1</actionID><brand>brand1</brand><effTime>effTime1</effTime><expireTime>expireTime1</expireTime><feeUser_ID>feeUserId1</feeUser_ID><destUser_ID>destUserId1</destUser_ID><actionReasonID>actionId1</actionReasonID><servType>servType1</servType><subServType>subServType1</subServType><SPID>spId1</SPID><SPServID>spServId1</SPServID><accessMode>accessMode1</accessMode><servParamInfo><para_num>0</para_num><para_info><para_name></para_name><para_value></para_value></para_info></servParamInfo><feeType>feeType1</feeType></subscriptionInfo></reqBody><reqBody><oprNumb>210001BIP2B518130410172224420909</oprNumb><subscriptionInfo><oprTime>oprTime2</oprTime><actionID>actionId2</actionID><brand>brand2</brand><effTime>effTime2</effTime><expireTime>expireTime2</expireTime><feeUser_ID>feeUserId2</feeUser_ID><destUser_ID>destUserId2</destUser_ID><actionReasonID>actionId2</actionReasonID><servType>servType2</servType><subServType>subServType2</subServType><SPID>spId2</SPID><SPServID>spServId2</SPServID><accessMode>accessMode2</accessMode><servParamInfo><para_num>0</para_num><para_info><para_name></para_name><para_value></para_value></para_info></servParamInfo><feeType>feeType2</feeType></subscriptionInfo></reqBody></batchSyncOrderRelationReq>]]></SvcCont></InterBOSS>解码代码如下:复制代码代码如下:@XmlRootElement(name = "batchSyncOrderRelationReq")@XmlAccessorType(XmlAccessType.FIELD)public class BatchSyncOrderRelationReq extends BossMessage<BatchSyncOrderRelationReq> {@XmlElement(name = "msgTransactionID")private String msgTransactionId = "";@XmlElement(name = "reqNum")private String reqNum = "";@XmlElement(name = "reqBody")private List<BatchSyncOrderRelationReqBody> reqBodyList;public BatchSyncOrderRelationReq() {}public String getMsgTransactionId() {return this.msgTransactionId;}public void setMsgTransactionId(String msgTransactionId) {this.msgTransactionId = msgTransactionId;}public String getReqNum() {return this.reqNum;}public void setReqNum(String reqNum) {this.reqNum = reqNum;}public List<BatchSyncOrderRelationReqBody> getReqBodyList() {return this.reqBodyList;}public void setReqBodyList(List<BatchSyncOrderRelationReqBody> reqBodyList) {this.reqBodyList = reqBodyList;}@Overridepublic BatchSyncOrderRelationReq Deserialized(String interBossXmlContent) throws BusinessException { try {// deserialized for headJAXBContext jaxbCxt4Head = JAXBContext.newInstance(MessageHead.class);Unmarshaller unmarshaller4Head = jaxbCxt4Head.createUnmarshaller();MessageHead head = (MessageHead) unmarshaller4Head.unmarshal(new StringReader(interBossXmlContent)); // deserialized for SyncOrderRelationReq bodyJAXBContext jaxbCxt4Body = JAXBContext.newInstance(BatchSyncOrderRelationReq.class);Unmarshaller unmarshaller4Body = jaxbCxt4Body.createUnmarshaller();BatchSyncOrderRelationReq batchSyncOrderRelationReq = (BatchSyncOrderRelationReq)unmarshaller4Body.unmarshal(new StringReader(head.getSvcCont().trim()));batchSyncOrderRelationReq.setHead(head);return batchSyncOrderRelationReq;} catch (JAXBException e) {throw new BusinessException("SyncOrderRelationReq.Deserialized() Error!(" + interBossXmlContent + ")", e);}}}复制代码代码如下:@XmlAccessorType(XmlAccessType.FIELD)public class BatchSyncOrderRelationReqBody {@XmlElement(name = "oprNumb")private String oprNumb = "";@XmlElement(name = "subscriptionInfo")private SubscriptionInfo subscriptionInfo;public BatchSyncOrderRelationReqBody(){}public BatchSyncOrderRelationReqBody(String oprNumb, SubscriptionInfo subscriptionInfo) {this.oprNumb = oprNumb;this.subscriptionInfo = subscriptionInfo;}public String getOprNumb() {return this.oprNumb;}public void setOprNumb(String oprNumb) {this.oprNumb = oprNumb;}public SubscriptionInfo getSubscriptionInfo() {return this.subscriptionInfo;}public void setSubscriptionInfo(SubscriptionInfo subscriptionInfo) {this.subscriptionInfo = subscriptionInfo;}}复制代码代码如下:@XmlAccessorType(XmlAccessType.FIELD)public class SubscriptionInfo {@XmlElement(name = "oprTime")private String oprTime = "";@XmlElement(name = "actionID")private String actionId = "";@XmlElement(name = "brand")private String brand = "";@XmlElement(name = "effTime")private String effTime = "";@XmlElement(name = "expireTime")private String expireTime = "";@XmlElement(name = "feeUser_ID")private String feeUserId = "";@XmlElement(name = "destUser_ID")private String destUserId = "";@XmlElement(name = "actionReasonID") private String actionReasonId = "";@XmlElement(name = "servType")private String servType = "";@XmlElement(name = "subServType") private String subServType = "";@XmlElement(name = "SPID")private String spId = "";@XmlElement(name = "SPServID")private String spServId = "";@XmlElement(name = "accessMode")private String accessMode = "";@XmlElement(name = "feeType")private String feeType = "";public SubscriptionInfo() {}public SubscriptionInfo(String oprTime,String actionId,String brand,String effTime,String expireTime,String feeUserId,String destUserId,String actionReasonId,String servType,String subServType,String spId,String spServId,String accessMode,String feeType) {this.oprTime = oprTime;this.actionId = actionId;this.brand = brand;this.effTime = effTime;this.expireTime = expireTime;this.feeUserId = feeUserId;this.destUserId = destUserId;this.actionReasonId = actionReasonId;this.servType = servType;this.subServType = subServType;this.spId = spId;this.spServId = spServId;this.accessMode = accessMode;this.feeType = feeType;}public String getOprTime() {return this.oprTime;}public void setOprTime(String oprTime) {this.oprTime = oprTime;}public String getActionId() {return this.actionId;}public void setActionId(String actionId) {this.actionId = actionId;}public String getBrand() {return this.brand;}public void setBrand(String brand) {this.brand = brand;}public String getEffTime() {return this.effTime;}public void setEffTime(String effTime) {this.effTime = effTime;}public String getExpireTime() {return this.expireTime;}public void setExpireTime(String expireTime) { this.expireTime = expireTime;}public String getFeeUserId() {return this.feeUserId;}public void setFeeUserId(String feeUserId) { this.feeUserId = feeUserId;}public String getDestUserId() {return this.destUserId;}public void setDestUserId(String destUserId) { this.destUserId = destUserId;}public String getActionReasonId() {return this.actionReasonId;}public void setActionReasonId(String actionReasonId) { this.actionReasonId = actionReasonId;}public String getServType() {return this.servType;}public void setServType(String servType) {this.servType = servType;}public String getSubServType() {return this.subServType;}public void setSubServType(String subServType) {this.subServType = subServType;}public String getSpId() {return this.spId;}public void setSpId(String spId) {this.spId = spId;}public String getSpServId() {return this.spServId;}public void setSpServId(String spServId) {this.spServId = spServId;}public String getAccessMode() {return this.accessMode;}public void setAccessMode(String accessMode) {this.accessMode = accessMode;}public String getFeeType() {return this.feeType;}public void setFeeType(String feeType) {this.feeType = feeType;}}。
详解Java解析XML的四种方法
详解Java解析XML的四种方法XML现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便。
对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),具体可参阅w3c官方网站文档获取更多信息。
XML在不同的语言里解析方式都是一样的,只不过实现的语法不同而已。
基本的解析方式有两种,一种叫SAX,另一种叫DOM。
SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。
假设我们XML的内容和结构如下:<?xml version="1.0" encoding="UTF-8"?><employees><employee><name>ddviplinux</name><sex>m</sex><age>30</age></employee></employees>本文使用JAVA语言来实现DOM与SAX的XML文档生成与解析。
首先定义一个操作XML文档的接口XmlDocument 它定义了XML文档的建立与解析的接口。
package com.alisoft.facepay.framework.bean;public interface XmlDocument {public void createXml(String fileName);public void parserXml(String fileName);}1.DOM生成和解析XML文档为XML文档的已解析版本定义了一组接口。
JAVA 解析XML 文件的三种解析方法
创建解析XML文件的三种解析方法1、第一种用w3c解析package w3c;import java.io.File;import java.io.FileOutputStream;import java.util.Random;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;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 w3c {public static void main(String[] args) throws Exception{ createXml();}//创建XML文档并创建节点public static void createXml() throws Exception{//获取XML解析器工厂类DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//获取XML解析器DocumentBuilder db = dbf.newDocumentBuilder();//获取操作的document对象Document document = db.newDocument();//设置XML文件的版本document.setXmlVersion("1.0");//创建根节点Element root = document.createElement("students");//将根节点添加到document对象中document.appendChild(root);//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//循环添加数据for(int i = 0 ;i < 20 ; i++){//创建根元素节点Element rootelement = document.createElement("student");//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}//设置根元素节点的属性rootelement.setAttribute("id",id);//将根元素节点添加到根节点中root.appendChild(rootelement);//设置元素节点Element name = document.createElement("name");Element sex = document.createElement("sex");Element age = document.createElement("age");Element phone = document.createElement("phone");//给元素节点赋值name.setTextContent(nameList[newRandom().nextInt(nameList.length)]);sex.setTextContent(sexList[newRandom().nextInt(sexList.length)]);age.setTextContent(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setTextContent("0756-"+tel);//将元素节点添加到根元素节点中rootelement.appendChild(name);rootelement.appendChild(sex);rootelement.appendChild(age);rootelement.appendChild(phone);}//开始把Document映射到文件TransformerFactory transFactory =TransformerFactory.newInstance();Transformer transFormer = transFactory.newTransformer();//生成的XML文件File file = new File("w3c.xml");//判断XML文件存不存在,如果不存在则创建if(file.exists()){file.createNewFile();}//设置是否添加空格transFormer.setOutputProperty(OutputKeys.INDENT, "yes");//设置输出文件的格式transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");//输出XML文件transFormer.transform(new DOMSource(document), newStreamResult(new FileOutputStream(file)));//输出XML文件的路径System.out.println(file.getAbsolutePath());}//解析XML文档public static void resolving() throws Exception{//获取XML解析器工厂类DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//获取XML解析器DocumentBuilder db = dbf.newDocumentBuilder();//获取操作的document对象Document document = db.parse(new File("w3c.xml"));//获取XML文件的根元素节点NodeList root = document.getElementsByTagName("student");//循环根元素节点信息for(int i = 0 ; i < root.getLength() ;i++){Element student = (Element)root.item(i);System.err.println("id = "+student.getAttribute("id")+" name = "+student.getElementsByTagName("name").item(0).getTextContent()+" sex = "+student.getElementsByTagName("sex").item(0).getTextContent()+" age = "+student.getElementsByTagName("age").item(0).getTextContent()+" phone = "+student.getElementsByTagName("phone").item(0).getTextContent());}}}2、第二种用jdom解析package jdom;import java.io.FileOutputStream;import java.util.Iterator;import java.util.List;import java.util.Random;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 jdom {private static String xmlpath = "jdom.xml";public static void main(String[] args) throws Exception{ //resolving();createXml();}//创建XML文件并添加节点public static void createXml() throws Exception{ //创建document对象Document document = new Document();//创建根节点Element root = new Element("students");//将根节点添加到document对象中document.addContent(root);for(int i = 0 ;i < 20 ; i++){//创建根元素节点Element student = new Element("student");//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}//设置跟元素节点的属性student.setAttribute("id",id);//将根元素节点添加到根节点中root.addContent(student);//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//创建元素节点Element name = new Element("name");Element sex = new Element("sex");Element age =new Element("age");Element phone = new Element("phone");//设置根元素节点的文本值name.setText(nameList[newRandom().nextInt(nameList.length)]);sex.setText(sexList[new Random().nextInt(sexList.length)]);age.setText(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setText("0756-"+tel);//将元素节点添加到根元素节点中student.addContent(name);student.addContent(sex);student.addContent(age);student.addContent(phone);}//设置XML输出排版Format format = Format.getPrettyFormat();XMLOutputter out = new XMLOutputter(format);//输出XML文件out.output(document, new FileOutputStream(xmlpath));}//解析XML文档@SuppressWarnings("rawtypes")public static void resolving() throws Exception{//获取XML解析器SAXBuilder builder = new SAXBuilder();//获取document对象Document doucment = builder.build(xmlpath);//获取根节点Element students = doucment.getRootElement();//获取根元素节点List studentList = students.getChildren("student");//循环获取元素文本值,第一种方法for(int i = 0 ; i< studentList.size() ; i++ ){Element student = (Element)studentList.get(i);System.out.println("id ="+student.getAttributeValue("id")+" name = "+student.getChildText("name")+" sex = "+student.getChildText("sex")+" age = "+student.getChildText("age")+" phone = "+student.getChildText("phone"));}System.err.println("\n---------------------------------------------------------------------");//循环获取元素文本值,第二种方法for(Iterator iter=studentList.iterator();iter.hasNext();){ Element student = (Element)iter.next();System.out.println("id ="+student.getAttributeValue("id")+" name = "+student.getChildText("name")+" sex = "+student.getChildText("sex")+" age = "+student.getChildText("age")+" phone = "+student.getChildText("phone"));}}}3、第三种用dom4j解析package dom4j;import java.io.File;import java.io.FileWriter;import java.util.Iterator;import java.util.List;import java.util.Random;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class dom4j {private static String xmlpath = "dom4j.xml";public static void main(String[] args)throws Exception{//createXml();resolving();}public static void createXml() throws Exception{//创建document对象Document document = DocumentHelper.createDocument();//创建根节点Element root = DocumentHelper.createElement("studnets");//将根节点添加到document对象中document.setRootElement(root);for(int i = 0 ;i < 20 ; i++){//创建根元素节点并将根元素节点添加到根节点中Element student = root.addElement("student");//设置根元素节点的值//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}student.addAttribute("id",id);//创建元素节点并将元素节点添加到根元素节点中Element name = student.addElement("name");Element sex = student.addElement("sex");Element age = student.addElement("age");Element phone = student.addElement("phone");//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//设置元素节点的文本值name.setText(nameList[newRandom().nextInt(nameList.length)]);sex.setText(sexList[new Random().nextInt(sexList.length)]);age.setText(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setText("0756-"+tel);}//设置XML文件输出的格式OutputFormat format = new OutputFormat("\t", true);format.setEncoding("utf-8");XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlpath), format);//输出XML文件xmlWriter.write(document);xmlWriter.close();}//解析XML文件@SuppressWarnings("rawtypes")public static void resolving() throws Exception{//获取XML解析器SAXReader saxReader = new SAXReader();//获取document对象Document document = saxReader.read(new File(xmlpath));//获取根节点Element root = document.getRootElement();//获取根元素节点List chindList = root.elements();//循环获取元素文本值,第一种方法for(Iterator iter = chindList.iterator(); iter.hasNext();){ Element student =(Element)iter.next();System.out.println("id = "+student.attributeValue("id")+" name = "+student.elementText("name")+" sex = "+student.elementText("sex")+" age = "+student.elementText("age")+" phone = "+student.elementText("phone"));}System.err.println("\n---------------------------------------------------------------------");//循环获取元素文本值,第二种方法for(int i = 0 ; i< chindList.size() ; i++ ){Element student = (Element)chindList.get(i);System.out.println("id = "+student.attributeValue("id")+" name = "+student.elementText("name")+" sex = "+student.elementText("sex")+" age = "+student.elementText("age")+" phone = "+student.elementText("phone"));}}}。
JAVA 解析XML 文件的三种解析方法
创建解析XML文件的三种解析方法1、第一种用w3c解析package w3c;import java.io.File;import java.io.FileOutputStream;import java.util.Random;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;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 w3c {public static void main(String[] args) throws Exception{ createXml();}//创建XML文档并创建节点public static void createXml() throws Exception{//获取XML解析器工厂类DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//获取XML解析器DocumentBuilder db = dbf.newDocumentBuilder();//获取操作的document对象Document document = db.newDocument();//设置XML文件的版本document.setXmlVersion("1.0");//创建根节点Element root = document.createElement("students");//将根节点添加到document对象中document.appendChild(root);//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//循环添加数据for(int i = 0 ;i < 20 ; i++){//创建根元素节点Element rootelement = document.createElement("student");//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}//设置根元素节点的属性rootelement.setAttribute("id",id);//将根元素节点添加到根节点中root.appendChild(rootelement);//设置元素节点Element name = document.createElement("name");Element sex = document.createElement("sex");Element age = document.createElement("age");Element phone = document.createElement("phone");//给元素节点赋值name.setTextContent(nameList[newRandom().nextInt(nameList.length)]);sex.setTextContent(sexList[newRandom().nextInt(sexList.length)]);age.setTextContent(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setTextContent("0756-"+tel);//将元素节点添加到根元素节点中rootelement.appendChild(name);rootelement.appendChild(sex);rootelement.appendChild(age);rootelement.appendChild(phone);}//开始把Document映射到文件TransformerFactory transFactory =TransformerFactory.newInstance();Transformer transFormer = transFactory.newTransformer();//生成的XML文件File file = new File("w3c.xml");//判断XML文件存不存在,如果不存在则创建if(file.exists()){file.createNewFile();}//设置是否添加空格transFormer.setOutputProperty(OutputKeys.INDENT, "yes");//设置输出文件的格式transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");//输出XML文件transFormer.transform(new DOMSource(document), newStreamResult(new FileOutputStream(file)));//输出XML文件的路径System.out.println(file.getAbsolutePath());}//解析XML文档public static void resolving() throws Exception{//获取XML解析器工厂类DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//获取XML解析器DocumentBuilder db = dbf.newDocumentBuilder();//获取操作的document对象Document document = db.parse(new File("w3c.xml"));//获取XML文件的根元素节点NodeList root = document.getElementsByTagName("student");//循环根元素节点信息for(int i = 0 ; i < root.getLength() ;i++){Element student = (Element)root.item(i);System.err.println("id = "+student.getAttribute("id")+" name = "+student.getElementsByTagName("name").item(0).getTextContent()+" sex = "+student.getElementsByTagName("sex").item(0).getTextContent()+" age = "+student.getElementsByTagName("age").item(0).getTextContent()+" phone = "+student.getElementsByTagName("phone").item(0).getTextContent());}}}2、第二种用jdom解析package jdom;import java.io.FileOutputStream;import java.util.Iterator;import java.util.List;import java.util.Random;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 jdom {private static String xmlpath = "jdom.xml";public static void main(String[] args) throws Exception{ //resolving();createXml();}//创建XML文件并添加节点public static void createXml() throws Exception{ //创建document对象Document document = new Document();//创建根节点Element root = new Element("students");//将根节点添加到document对象中document.addContent(root);for(int i = 0 ;i < 20 ; i++){//创建根元素节点Element student = new Element("student");//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}//设置跟元素节点的属性student.setAttribute("id",id);//将根元素节点添加到根节点中root.addContent(student);//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//创建元素节点Element name = new Element("name");Element sex = new Element("sex");Element age =new Element("age");Element phone = new Element("phone");//设置根元素节点的文本值name.setText(nameList[newRandom().nextInt(nameList.length)]);sex.setText(sexList[new Random().nextInt(sexList.length)]);age.setText(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setText("0756-"+tel);//将元素节点添加到根元素节点中student.addContent(name);student.addContent(sex);student.addContent(age);student.addContent(phone);}//设置XML输出排版Format format = Format.getPrettyFormat();XMLOutputter out = new XMLOutputter(format);//输出XML文件out.output(document, new FileOutputStream(xmlpath));}//解析XML文档@SuppressWarnings("rawtypes")public static void resolving() throws Exception{//获取XML解析器SAXBuilder builder = new SAXBuilder();//获取document对象Document doucment = builder.build(xmlpath);//获取根节点Element students = doucment.getRootElement();//获取根元素节点List studentList = students.getChildren("student");//循环获取元素文本值,第一种方法for(int i = 0 ; i< studentList.size() ; i++ ){Element student = (Element)studentList.get(i);System.out.println("id ="+student.getAttributeValue("id")+" name = "+student.getChildText("name")+" sex = "+student.getChildText("sex")+" age = "+student.getChildText("age")+" phone = "+student.getChildText("phone"));}System.err.println("\n---------------------------------------------------------------------");//循环获取元素文本值,第二种方法for(Iterator iter=studentList.iterator();iter.hasNext();){ Element student = (Element)iter.next();System.out.println("id ="+student.getAttributeValue("id")+" name = "+student.getChildText("name")+" sex = "+student.getChildText("sex")+" age = "+student.getChildText("age")+" phone = "+student.getChildText("phone"));}}}3、第三种用dom4j解析package dom4j;import java.io.File;import java.io.FileWriter;import java.util.Iterator;import java.util.List;import java.util.Random;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class dom4j {private static String xmlpath = "dom4j.xml";public static void main(String[] args)throws Exception{//createXml();resolving();}public static void createXml() throws Exception{//创建document对象Document document = DocumentHelper.createDocument();//创建根节点Element root = DocumentHelper.createElement("studnets");//将根节点添加到document对象中document.setRootElement(root);for(int i = 0 ;i < 20 ; i++){//创建根元素节点并将根元素节点添加到根节点中Element student = root.addElement("student");//设置根元素节点的值//声明参数IDString id ="";//循环生成一个9为的随机ID数for(int j = 0; j< 9 ; j ++ ){id += new Random().nextInt(8)+1;}student.addAttribute("id",id);//创建元素节点并将元素节点添加到根元素节点中Element name = student.addElement("name");Element sex = student.addElement("sex");Element age = student.addElement("age");Element phone = student.addElement("phone");//声明一个姓名的数组String nameList[] = {"吕布","赵云","马超","张飞","关羽","许褚","孙策","周瑜","夏侯渊","张颌","于禁","黄忠","典韦","曹仁","程普"};String sexList[] = {"男","女"};//设置元素节点的文本值name.setText(nameList[newRandom().nextInt(nameList.length)]);sex.setText(sexList[new Random().nextInt(sexList.length)]);age.setText(new Random().nextInt(20)+20+"");String tel ="";for(int k = 0; k< 7 ; k++ ){tel += new Random().nextInt(9);}phone.setText("0756-"+tel);}//设置XML文件输出的格式OutputFormat format = new OutputFormat("\t", true);format.setEncoding("utf-8");XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlpath), format);//输出XML文件xmlWriter.write(document);xmlWriter.close();}//解析XML文件@SuppressWarnings("rawtypes")public static void resolving() throws Exception{//获取XML解析器SAXReader saxReader = new SAXReader();//获取document对象Document document = saxReader.read(new File(xmlpath));//获取根节点Element root = document.getRootElement();//获取根元素节点List chindList = root.elements();//循环获取元素文本值,第一种方法for(Iterator iter = chindList.iterator(); iter.hasNext();){ Element student =(Element)iter.next();System.out.println("id = "+student.attributeValue("id")+" name = "+student.elementText("name")+" sex = "+student.elementText("sex")+" age = "+student.elementText("age")+" phone = "+student.elementText("phone"));}System.err.println("\n---------------------------------------------------------------------");//循环获取元素文本值,第二种方法for(int i = 0 ; i< chindList.size() ; i++ ){Element student = (Element)chindList.get(i);System.out.println("id = "+student.attributeValue("id")+" name = "+student.elementText("name")+" sex = "+student.elementText("sex")+" age = "+student.elementText("age")+" phone = "+student.elementText("phone"));}}}。
java xml注解解析
java xml注解解析在Java 中,XML 注解解析通常是通过使用JAXB(Java Architecture for XML Binding)实现的。
JAXB 提供了一种方便的方式,允许Java 类和XML 数据进行映射。
下面是一个简单的示例,演示如何使用JAXB 注解解析XML 数据。
考虑以下XML 数据:```xml<person><id>1</id><name>John Doe</name><age>30</age></person>```现在,我们将创建一个Java 类`Person`,并使用JAXB 注解将其映射到上述XML 结构。
```javaimport javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Person {private int id;private String name;private int age;@XmlElementpublic int getId() {return id;}public void setId(int id) {this.id = id;}@XmlElementpublic String getName() {return name;}public void setName(String name) { = name;}@XmlElementpublic int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}}```在上述代码中,我们使用`@XmlRootElement` 注解标记`Person` 类为XML 根元素。
java解析xml详解及示例
java解析xml详解及示例java 解析xml的几种方法第一种:DOMDOM的全称是Document Object Model,也即文档对象模型。
在应用程序中,基于DOM 的XML分析器将一个XML文档转换成一个对象模型的集合(通常称DOM树),应用程序正是通过对这个对象模型的操作,来实现对XML文档数据的操作。
通过DOM接口,应用程序可以在任何时候访问XML文档中的任何一部分数据,因此,这种利用DOM接口的机制也被称作随机访问机制。
DOM接口提供了一种通过分层对象模型来访问XML文档信息的方式,这些分层对象模型依据XML的文档结构形成了一棵节点树。
无论XML文档中所描述的是什么类型的信息,即便是制表数据、项目列表或一个文档,利用DOM所生成的模型都是节点树的形式。
也就是说,DOM强制使用树模型来访问XML文档中的信息。
由于XML本质上就是一种分层结构,所以这种描述方法是相当有效的。
DOM树所提供的随机访问方式给应用程序的开发带来了很大的灵活性,它可以任意地控制整个XML文档中的内容。
然而,由于DOM 分析器把整个XML文档转化成DOM树放在了内存中,因此,当文档比较大或者结构比较复杂时,对内存的需求就比较高。
而且,对于结构复杂的树的遍历也是一项耗时的操作。
所以,DOM分析器对机器性能的要求比较高,实现效率不十分理想。
不过,由于DOM分析器所采用的树结构的思想与XML 文档的结构相吻合,同时鉴于随机访问所带来的方便,因此,DOM分析器还是有很广泛的使用价值的。
Java代码import java.io.File;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;public class DomT est1{public static void main(String[] args) throws Exception{// step 1: 获得dom解析器工厂(工作的作用是用于创建具体的解析器)DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();// System.out.println("class name: " + dbf.getClass().getName());// step 2:获得具体的dom解析器DocumentBuilder db = dbf.newDocumentBuilder();// System.out.println("class name: " + db.getClass().getName());// step3: 解析一个xml文档,获得Document对象(根结点)Document document = db.parse(new File("candidate.xml"));NodeList list = document.getElementsByTagName("PERSON");for(int i = 0; i < list.getLength(); i++){Element element = (Element)list.item(i);String content =element.getElementsByTagName("NAME").item(0).getFirstC hild().getNodeValue();System.out.println("name:" + content);content =element.getElementsByTagName("ADDRESS").item(0).getFir stChild().getNodeValue(); System.out.println("address:" + content);content =element.getElementsByTagName("TEL").item(0).getFirstChil d().getNodeValue();System.out.println("tel:" + content);content =element.getElementsByTagName("FAX").item(0).getFirstChil d().getNodeValue();System.out.println("fax:" + content);content =element.getElementsByTagName("EMAIL").item(0).getFirstC hild().getNodeValue();System.out.println("email:" + content);System.out.println("--------------------------------------");}}}Java代码import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Attr;import /doc/723478280.html,ment;import org.w3c.dom.Document;import org.w3c.dom.Element;import/doc/723478280.html,dNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;/*** 使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上* @author*/public class DomT est3{public static void main(String[] args) throws Exception{DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document doc = db.parse(new File("student.xml"));//获得根元素结点Element root = doc.getDocumentElement();parseElement(root);}private static void parseElement(Element element){String tagName = element.getNodeName();NodeList children = element.getChildNodes();System.out.print("<" + tagName);//element元素的所有属性所构成的NamedNodeMap对象,需要对其进行判断 NamedNodeMap map = element.getAttributes();//如果该元素存在属性if(null != map){{//获得该元素的每一个属性Attr attr = (Attr)map.item(i);String attrName = attr.getName();String attrValue = attr.getValue();System.out.print(" " + attrName + "=\"" + attrValue + "\""); } }System.out.print(">");for(int i = 0; i < children.getLength(); i++){Node node = children.item(i);//获得结点的类型short nodeType = node.getNodeType();if(nodeType == Node.ELEMENT_NODE){//是元素,继续递归parseElement((Element)node);}else if(nodeType == Node.TEXT_NODE){//递归出口System.out.print(node.getNodeValue());}else if(nodeType == /doc/723478280.html,MENT_NODE) {System.out.print("System.out.print(data);System.out.print("-->");}}System.out.print("");}}第二种 sax:SAX的全称是Simple APIs for XML,也即XML简单应用程序接口。
java解析xml的方式
1.各种方式的详解1)DOM(JAXP Crimson解析器)DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准。
DOM是以层次结构组织的节点或信息片断的集合。
这个层次结构允许开发人员在树中寻找特定信息。
分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作。
由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的。
DOM 以及广义的基于树的处理具有几个优点。
首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改。
它还可以在任何时候在树中上下导航,而不是像SAX那样是一次性的处理。
DOM使用起来也要简单得多。
2)SAXSAX处理的优点非常类似于流媒体的优点。
分析能够立即开始,而不是等待所有的数据被处理。
而且,由于应用程序只是在读取数据时检查数据,因此不需要将数据存储在内存中。
这对于大型文档来说是个巨大的优点。
事实上,应用程序甚至不必解析整个文档;它可以在某个条件得到满足时停止解析。
一般来说,SAX 还比它的替代者DOM快许多。
选择DOM还是选择SAX?对于需要自己编写代码来处理XML文档的开发人员来说,选择DOM还是SAX解析模型是一个非常重要的设计决策。
DOM采用建立树形结构的方式访问XML文档,而SAX采用的事件模型。
DOM解析器把XML文档转化为一个包含其内容的树,并可以对树进行遍历。
用DOM 解析模型的优点是编程容易,开发人员只需要调用建树的指令,然后利用navigation APIs访问所需的树节点来完成任务。
可以很容易的添加和修改树中的元素。
然而由于使用DOM解析器的时候需要处理整个XML文档,所以对性能和内存的要求比较高,尤其是遇到很大的XML文件的时候。
由于它的遍历能力,DOM解析器常用于XML文档需要频繁的改变的服务中。
SAX解析器采用了基于事件的模型,它在解析XML文档的时候可以触发一系列的事件,当发现给定的tag的时候,它可以激活一个回调方法,告诉该方法制定的标签已经找到。
java解析xml
java解析xmljava解析xmlxml是java⼯程⾥常⽤的配置⽂件格式,具有很强的表达⼒。
dom4j是经典的xml解析器,本⽂以此为例,记录java解析xml的过程。
⼀、创建$ mvn archetype:generate# mu模板就⽤最常⽤的maven-archetype-quickstartConfirm properties configuration:groupId: .zjuartifactId: dom4jdemoversion: 1.0-SNAPSHOTpackage: .zjuY: : y⼆、pom依赖项<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><!-- 在xPath解析式要依赖这个包 --><dependency><groupId>jaxen</groupId><artifactId>jaxen</artifactId><version>1.2.0</version></dependency></dependencies>三、⼯程结构➜ dom4jdemo tree.├── pom.xml├── resources│└── test.xml # 待解析的xml⽂件└── src├── main│└── java│└── cn│└── edu│└── zju│└── App.java└── test└── java└── cn└── edu└── zju└── AppTest.java四、待解析的xml⽂件test.xml<?xml version="1.0" encoding="UTF-8" ?><resources><product name="QQ"><account id="123456789"><nickname>qq1</nickname><password>123</password><level>56</level></account><account id="987654321"><nickname>qq2</nickname><password>456</password><level>12</level></account></product><product name="Netease"><account id="Tom"><password>pwdOfTom</password><capacity>1024</capacity></account><account id="Jim"><password>pwdOfJim</password><capacity>2560</capacity></account></product></resources>五、代码App.javapackage .zju;import org.dom4j.*;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import org.dom4j.xpath.DefaultXPath;import java.io.FileWriter;import java.io.IOException;import java.util.Iterator;import java.util.List;/*** Hello world!*/public class App {private Document document;App() {SAXReader reader = new SAXReader();try {document = reader.read("resources/test.xml");} catch (DocumentException e) {e.printStackTrace();}}void xPathParse() {// ⽤xpath解析XPath xPath = new DefaultXPath("/resources/product[@name='QQ']/account[@id='987654321']/password"); List<Element> list = xPath.selectNodes(document.getRootElement());for (Element element : list) {System.out.println(element.getTextTrim());}}void normalParse() {// 解析每个节点List<Element> products = document.getRootElement().selectNodes("/resources/product");Iterator<Element> iterator = products.iterator();while (iterator.hasNext()) {Element product = iterator.next();// 获得属性System.out.println(product.attributeValue("name"));List<Element> accounts = product.selectNodes("account");for (Element account : accounts) {System.out.println("--" + account.attributeValue("id"));// 获得值System.out.println("-----" + account.elementTextTrim("password"));}}}void generate() {Document doc = DocumentHelper.createDocument();Element root = doc.addElement("people");Element p1 = root.addElement("p1");p1.addAttribute("id", "12345");p1.addElement("sex").setText("male");p1.addElement("age").setText("18");Element p2 = root.addElement("p2");p2.addAttribute("id", "67890");p2.addElement("sex").setText("female");p2.addElement("age").setText("26");XMLWriter xmlWriter = new XMLWriter();try {xmlWriter.setWriter(new FileWriter("resources/out.xml"));xmlWriter.write(doc);} catch (IOException e) {e.printStackTrace();} finally {try {xmlWriter.flush();xmlWriter.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) {App app = new App();app.xPathParse();app.normalParse();app.generate();}}六、运⾏输出456QQ--123456789-----123--987654321-----456Netease--Tom-----pwdOfTom--Jim-----pwdOfJim七、⽣成⽂件resources/out.xml<?xml version="1.0" encoding="UTF-8"?><people><p1 id="12345"><sex>male</sex><age>18</age></p1><p2 id="67890"><sex>female</sex><age>26</age></p2></people>⼋、⼩结感觉java的代码都可以望⽂成义,看着代码和注释就能明⽩在⼲什么。
java解析xml文档---通过XmlPullParser解析方式
java解析xml⽂档---通过XmlPullParser解析⽅式 1package com.zx;23import java.io.FileInputStream;4import java.io.IOException;5import java.util.ArrayList;6import java.util.List;78import org.json.JSONException;9import org.xmlpull.v1.XmlPullParser;10import org.xmlpull.v1.XmlPullParserException;11import org.xmlpull.v1.XmlPullParserFactory;12131415class MyDay17Xml {1617public static void main(String []args) throws JSONException{1819 }2021public static List<Person> PullParserXml() throws XmlPullParserException, IOException {22//数据定义23 List<Person> list=null;24 Person person=null;25//获得xmlpullparser对象26 XmlPullParserFactory factory=XmlPullParserFactory.newInstance();27 XmlPullParser parser=factory.newPullParser();28//获取输⼊流29 FileInputStream fis=new FileInputStream("person.xml");30//设置流和字符集31 parser.setInput(fis,"utf-8");32//开始解析33int event=parser.getEventType();34while(event!=XmlPullParser.END_DOCUMENT){35switch (event){36/**37 * 开始标记,通常进⾏相关集合或者对象的初始化3839*/40case XmlPullParser.START_DOCUMENT:41 list=new ArrayList<Person>(); break;42case XmlPullParser.START_TAG:43 String tagName=parser.getName();44//得到属性标记通过getName45if("person".equals(tagName)){46 person=new Person();47//获得标记后的属性值通过getAttributeName和getAttributeValue两个⽅法48for(int i=0;i<parser.getAttributeCount();i++){49 String name=parser.getAttributeName(i);50 String value=parser.getAttributeValue(i);51if("id".equals(name)){52 person.setId(value);53 }54 }55 }else if("name".equals(tagName)){56//得到属性标记之后的值,通过nextText⽅法57 person.setName(parser.nextText());58 }else if("age".equals(tagName)){59 person.setAge(parser.nextText());60 } break;61case XmlPullParser.END_TAG:62if("person".equals(parser.getName())){63 list.add(person);64 person=null;65 } break;66 } event=parser.next();67 }68//解析结束,返回集合69return list;70 }7172 }73class Person{74private String name,age,id;7576public String getName() {77return name;78 }7980public void setName(String name) { = name;82 }8384public String getAge() {85return age;86 }8788public void setAge(String age) {89this.age = age;90 }9192public String getId() {93return id;94 }9596public void setId(String id) {97this.id = id;98 }99 }。
java解析xml文件
java解析xml⽂件⼀、SAX解析1、将要解析的xml⽂件为TestDom.xml<?xml version="1.0" encoding="utf-8"?><bookStore><book id="1" class="tonghua"><name>安徒⽣童话</name><author>安徒⽣</author><year>2008</year></book><book id="2" class="xiyouji"><name>西游记</name><author>罗贯中</author></book></bookStore>2、Book类package youth.hong.TestDom;public class Book {private String id = "";private String className = "";private String name = "";private String author = "";private String year = "";public Book(String id, String name, String author, String year) {super();this.id = id; = name;this.author = author;this.year = year;}public Book() {}@Overridepublic String toString() {return "Book [id=" + id + ", className=" + className + ", name=" + name + ", author=" + author + ", year=" + year + "]";}public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getYear() {return year;}public void setYear(String year) {this.year = year;}}3、解析xml的主类package youth.hong.Handler;import java.util.ArrayList;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import youth.hong.TestDom.Book;public class SAXHandler extends DefaultHandler{int bookIndex = 0;private List<Book> bookList = new ArrayList<Book>();private Book book = null;private String value = null;//⽤来标志解析开始@Overridepublic void startDocument() throws SAXException {System.out.println("解析开始");}//⽤来标志解析结束@Overridepublic void endDocument() throws SAXException {System.out.println("解析结束");}//⽤来遍历元素//开始标签@Overridepublic void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {if(qName.equals("book")) {bookIndex++;book = new Book();System.out.println("============================第" + bookIndex + "本书开始了=========================");//已知book下属性元素的名称//System.out.println(attributes.getValue("id"));for(int i = 0; i < attributes.getLength(); i++) {String name = attributes.getQName(i);if(name.equals("id")) {book.setId(attributes.getValue(i));}else if(name.equals("class")) {book.setClassName(attributes.getValue(i));}book.setId(attributes.getValue(i));//System.out.println(name);System.out.println("第" + bookIndex + "本书的" + attributes.getQName(i) + "是:" + attributes.getValue(i)/*attributes.getValue(Qname)*/); }}else if(!qName.equals("bookStore")) {System.out.print("第" + bookIndex + "本书的" + qName + "是:");}}//遍历标签内的内容@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {value = new String(ch,start,length);//如果标签下没有内容,如bookstore与book之间就没有内容,将不打印if(!value.trim().equals("")) {System.out.println(value);}}//遍历元素的结束标签@Overridepublic void endElement(String uri, String localName, String qName) throws SAXException {if(qName.equals("book")) {bookList.add(book);book = null;System.out.println("============================第" + bookIndex + "本书结束了========================="); }else if(qName.equals("name")) {book.setName(value);}else if(qName.equals("author")) {book.setAuthor(value);}else if(qName.equals("year")) {book.setYear(value);}}public List<Book> getBookList() {return bookList;}}4、测试类(包括创建xml⽂件)package youth.hong.TestDom;import java.io.File;import java.io.FileOutputStream;import java.util.List;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Result;import javax.xml.transform.Transformer;import javax.xml.transform.sax.SAXTransformerFactory;import javax.xml.transform.sax.TransformerHandler;import javax.xml.transform.stream.StreamResult;import org.xml.sax.helpers.AttributesImpl;import youth.hong.Handler.SAXHandler;public class SAXTest {public List<Book> parseXml() {SAXHandler saxhandler = null;SAXParserFactory parserFactory = SAXParserFactory.newInstance();try {SAXParser saxParser = parserFactory.newSAXParser();saxhandler = new SAXHandler();saxParser.parse("src/TestJDom/TestDom.xml", saxhandler);for (Book book : saxhandler.getBookList()) {System.out.println(book);}System.out.println();} catch (Exception e) {e.printStackTrace();};return saxhandler.getBookList();}/*** ⽣成xml⽂件*/public void createXml() {List<Book> bookList = this.parseXml();//转化⼯⼚SAXTransformerFactory tff = (SAXTransformerFactory)SAXTransformerFactory.newInstance();try {TransformerHandler handler = tff.newTransformerHandler();//转换器Transformer tf = handler.getTransformer();//设置输出编码为UTF-8tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");//输出格式缩进tf.setOutputProperty(OutputKeys.INDENT, "yes");//要输出的⽂件File file = new File("src/TestJDom/newBook.xml");//如果⽂件不存在就创建⼀个if(!file.exists()) {file.createNewFile();}Result result = new StreamResult(new FileOutputStream(file));//必须在result定义完再加⼊内容才有效handler.setResult(result);handler.startDocument();AttributesImpl atts = new AttributesImpl();handler.startElement("", "", "bookStore", atts);//遍历所有书籍将他们加⼊到xml中for(Book book : bookList) {atts.clear();/*** public void addAttribute(String uri,String localName,命名空间本地名String qName,元素名String type,元素类型String value)值*/atts.addAttribute("", "", "id", null, book.getId());atts.addAttribute("", "", "class", null, book.getClassName());//注意按照SAX模式解析xml⽂件的顺序去定义标签handler.startElement("", "", "book", atts);atts.clear();handler.startElement("", "", "name", atts);char[] ch = book.getName().toCharArray();handler.characters(ch, 0, ch.length);handler.endElement("", "", "name");handler.startElement("", "", "author", atts);ch = book.getAuthor().toCharArray();handler.characters(ch, 0, ch.length);handler.endElement("", "", "author");handler.startElement("", "", "year", atts);ch = book.getYear().toCharArray();handler.characters(ch, 0, ch.length);handler.endElement("", "", "year");handler.endElement("", "", "book");}handler.endElement("", "", "bookStore");handler.endDocument();} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {SAXTest saxTest = new SAXTest();//saxTest.createXml();saxTest.parseXml();}}5、⽣成newBook.xml⽂件<?xml version="1.0" encoding="utf-8"?><bookStore><book id="tonghua" class="tonghua"><name>安徒⽣童话</name><author>安徒⽣</author><year>2008</year></book><book id="xiyouji" class="xiyouji"><name>西游记</name><author>罗贯中</author><year/></book></bookStore>⼆、jdom解析1、解析与创建package youth.hong.TestJDom;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;import youth.hong.TestDom.Book;public class TestJDom {private static List<Book> bookList = new ArrayList<Book>();public void parseXML() {SAXBuilder saxBuilder = new SAXBuilder();try {Document document = saxBuilder.build(new InputStreamReader(new FileInputStream("src/TestJDom/TestDom.xml"),"utf-8"));/*Document document2 = saxBuilder.build(new FileReader("src/TestJDom/TestDom.xml"));*///没有字符编码,所以最好使⽤上⾯那种Element element = document.getRootElement();int i = 0;// elment.getAttributeValue()返回⼀个list对象List<Element> bookList = element.getChildren();// 遍历每个book的属性for (Element book : bookList) {Book bookEntity = new Book();i++;System.out.println("======================第" + i + "开始==========================");// 已知属性名// System.out.println(book.getAttributeValue("class"));List<Attribute> attrList = book.getAttributes();for (Attribute attribute : attrList) {System.out.println("属性名称:" + attribute.getName() + "----属性值是:" + attribute.getValue());if(attribute.getName().equals("id")) {bookEntity.setId(attribute.getValue());}else if(attribute.getName().equals("class")) {bookEntity.setClassName(attribute.getValue());}}List<Element> children = book.getChildren();for (Element element2 : children) {System.out.println("节点名--" + element2.getName() + "--节点值--" + element2.getValue());if(element2.getName().equals("name")) {bookEntity.setName(element2.getValue());}else if(element2.getName().equals("author")) {bookEntity.setAuthor(element2.getValue());}else if(element2.getName().equals("year")) {bookEntity.setYear(element2.getValue());}}System.out.println("======================第" + i + "结束=========================="); TestJDom.bookList.add(bookEntity);bookEntity = null;}// System.out.println(TestJDom.bookList.size());} catch (JDOMException | IOException e) {e.printStackTrace();}}public void createXML() {//创建⼀个root节点rssElement rss = new Element("rss");//定义version属性rss.setAttribute("version","2.0");//创建documentDocument document = new Document(rss);Element channel = new Element("channel");rss.addContent(channel);Element title = new Element("title");channel.addContent(title);title.setText("<java你好>");//title.addContent(new CDATA("<!--java你好-->"));Format format = Format.getCompactFormat();format.setIndent("");format.setEncoding("gbk");XMLOutputter outputer = new XMLOutputter(format);try {outputer.output(document, new FileOutputStream("src/TestJDom/JDomnews.xml")); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {TestJDom jd = new TestJDom();jd.parseXML();jd.createXML();}}2、Jdomnews.xml<?xml version="1.0" encoding="gbk"?><rss version="2.0"><channel><title><java你好></title></channel></rss>三、dom4j解析1、解析与创建package youth.hong.TestDom4J;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import youth.hong.TestDom.Book;public class Dom4JTest {private static List<Book> bookList = new ArrayList<Book>();//dom4j解析xml⽂档public void parseXML() {SAXReader reader = new SAXReader();try {Document document = reader.read(new File("src/TestJDom/TestDom.xml"));System.out.println(new File("src/TestJDom/TestDom.xml"));Element bookStore = document.getRootElement();Iterator<Element> it = bookStore.elementIterator();while(it.hasNext()) {System.out.println("===================某本书开始==================");Book bookEntity = new Book();Element book = it.next();List<Attribute> attrList = book.attributes();System.out.println("当前结点下节点的个数(包括空⽩的⽂本节点)" + book.nodeCount());for(Attribute attribute : attrList) {System.out.println("属性名:" + attribute.getName() + "属性值:" + attribute.getValue());if(attribute.getName().equals("id")) {bookEntity.setId(attribute.getValue());}else if(attribute.getName().equals("class")) {bookEntity.setClassName(attribute.getValue());}}Iterator<Element> itt = book.elementIterator();while(itt.hasNext()) {Element childNode = itt.next();System.out.println("节点名:" + childNode.getName() + "节点值:" + childNode.getStringValue());if(childNode.getName().equals("name")) {bookEntity.setName(childNode.getStringValue());}else if(childNode.getName().equals("author")) {bookEntity.setAuthor(childNode.getStringValue());}else if(childNode.getName().equals("year")) {bookEntity.setYear(childNode.getStringValue());}}bookList.add(bookEntity);bookEntity = null;System.out.println("===================某本书结束==================");System.out.println(bookList.size());}} catch (DocumentException e) {e.printStackTrace();}}//⽣成XML⽂档public void createXML() {Document document = DocumentHelper.createDocument();Element rss = document.addElement("rss");rss.addAttribute("version", "2.0");Element channel = rss.addElement("channel");Element title = channel.addElement("title");title.setText("<!--新闻要点-->");Element image = channel.addElement("image");Element imageTitle = image.addElement("title");imageTitle.setText("");Element link = image.addElement("link");link.setText("");Element url = image.addElement("url");url.setText("/img/logo-news.gif");File file = new File("src/TestJDom/news.xml");OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("GBK");try {XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);writer.setEscapeText(false);writer.write(document);} catch (UnsupportedEncodingException | FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {Dom4JTest d4j = new Dom4JTest();d4j.parseXML();d4j.createXML();}}2、创建的news.xml<?xml version="1.0" encoding="GBK"?><rss version="2.0"><channel><title><!--新闻要点--></title><image><title></title><link></link><url>/img/logo-news.gif</url></image></channel></rss>四、dom解析1、解析与创建package youth.hong.TestDom;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;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.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class TestDom {private static List<Book> bookSuffle = new ArrayList<Book>();/*** 获取DocumentBuilder对象*/public DocumentBuilder getDocumentBuilder() {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder documentBuilder = null;try {documentBuilder = dbf.newDocumentBuilder();} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();}return documentBuilder;}/*** dom⽅法解析Xml⽂件*/public void domParse() {try {Document document = getDocumentBuilder().parse("src/TestJDom/TestDom.xml"); NodeList bookList = document.getElementsByTagName("book");for(int i = 0; i < bookList.getLength(); i++) {String id = null;String name = null;String author = null;String year = null;//在不知道属性名称的情况下使⽤/*Node book = bookList.item(i);NamedNodeMap attrs = book.getAttributes();for(int j = 0; j < attrs.getLength(); j++) {Node attr = attrs.item(j);System.out.println(attr.getNodeName() + " " + attr.getNodeValue());}*///在知道属性名称的情况下使⽤/*Element book = (Element)bookList.item(i);String id = book.getAttribute("id");String className = book.getAttribute("class");System.out.println(id + " " + className);*/Node book = bookList.item(i);Element bookElement = (Element)book;id = bookElement.getAttribute("id");NodeList childNodes = book.getChildNodes();System.out.println(childNodes.getLength());for(int k = 0; k < childNodes.getLength(); k++) {Node childNode = childNodes.item(k);if(childNode.getNodeType() == Node.ELEMENT_NODE) {String value = childNode.getTextContent();String nodeName = childNode.getNodeName();switch(nodeName) {case "name" : name = value; value = null; break;case "author" : author = value; value = null; break;case "year" : year = value; value = null; break;}//System.out.println(childNode.getNodeName() + " " + childNode.getFirstChild().getNodeValue()); }}bookSuffle.add(new Book(id,name,author,year));//System.out.println();}for(int i = 0; i < bookSuffle.size(); i++) {System.out.println(bookSuffle.get(i));}} catch (SAXException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** ⽣成Xml⽂件,要创建多本书可以通过for循环来⽣成,但内容应当定义⼀个book的类去存储内容* @param args*/public void creatXml() {DocumentBuilder documentBuilder = this.getDocumentBuilder();//⽣成documentDocument document = documentBuilder.newDocument();//去掉standalone属性document.setXmlStandalone(true);//创建bookStore节点Element bookStore = document.createElement("bookStore");//创建book节点Element book1 = document.createElement("book");Element book2 = document.createElement("book");Element name1 = document.createElement("name");Element author1 = document.createElement("author");Element year1 = document.createElement("year");Element price1 = document.createElement("price");Element name2 = document.createElement("name");Element author2 = document.createElement("author");Element year2 = document.createElement("year");Element price2 = document.createElement("price");/*//创建⽂本节点Node nameText = document.createTextNode("七龙珠");//添加⽂本节点name.appendChild(nameText);*/name1.setTextContent("⽝夜叉");year1.setTextContent("2008");author1.setTextContent("⾼桥留美⼦");price1.setTextContent("200$");book1.appendChild(name1);book1.appendChild(author1);book1.appendChild(year1);book1.appendChild(price1);//为book节点添加属性idbook1.setAttribute("id", "1");//把book节点加⼊到bookStore节点中bookStore.appendChild(book1);name2.setTextContent("唐⼈街探案");year2.setTextContent("2016");author2.setTextContent("陈思成");price2.setTextContent("VIP会员免费");book2.appendChild(name2);book2.appendChild(author2);book2.appendChild(year2);book2.appendChild(price2);//添加第⼆个bookbookStore.appendChild(book2);//把节点bookStore加⼊到document中document.appendChild(bookStore);//使⽤TransformerFactoryTransformerFactory factory = TransformerFactory.newInstance();try {Transformer transformer = factory.newTransformer();//输⼊节点之间的换⾏transformer.setOutputProperty(OutputKeys.INDENT, "yes");//传⼊document,输出流⽣成xml⽂件transformer.transform(new DOMSource(document), new StreamResult(new File("bookCreate.xml"))); } catch (TransformerConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TransformerException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 主程序的⼊⼝* @param args*/public static void main(String[] args) {// TODO Auto-generated method stubTestDom testDom = new TestDom();testDom.domParse();testDom.creatXml();}}2、⽣成的bookCreate.xml<?xml version="1.0" encoding="UTF-8"?><bookStore><book id="1"><name>⽝夜叉</name><author>⾼桥留美⼦</author><year>2008</year><price>200$</price></book><book><name>唐⼈街探案</name><author>陈思成</author><year>2016</year><price>VIP会员免费</price></book></bookStore>。
Java解析XML编程
简介 解析器基础 文档对象模型(DOM) Simple API for XML(SAX) JDOM 结束语
简介
介绍 Java 语言中处理 XML 文档最常用的编程 接口 这里XML 处理工作是 解析 XML 文档。解析包 括读取 XML 文档并确定其结构和内容。三种 XML 解析器读取 XML 文档。创建解析器对象、 解析器处理 XML 文件、处理解析结果。使用不 同的方式完成这类常见的任务;将分析所涉及到 的标准以及什么时候应该使用这种或那种方法。
第一个示例应用程序
第一个应用程序是 DomOne.java, 代码完成四件事:
1.创建一个解析器对象 。 2.解析 XML 文件 。 3.打印 DOM 树的内容。 4.测试并运行。
关于 JAXP 的简单说明
JAXP,即 Java API for XML Parsing。JAXP 规定了 DOM 和 SAX 标准没有定义
内存少就是说您的机器没有太多内存只需要xml文档中少量元素或属性解析的信息只使用一次最后看一看jdomapijdom的内存使用比dom少但是不如sax文档对象模型domxml结构的一种通用接口dom的设计目标是提供一组对象和方法使程序员的工作更轻松
利用 Java 技术进行 XML 编程
涵盖了使用 Java 技术操作 XML 的基础知识。 常用的 XML API 并讨论如何解析、创建、操纵 和转换 XML 文档。 lmg
不必要的对象以及其他使用 DOM 解析器所担心的问题。
要记住,SAX 事件是 无状态的。换句话说,观察单个的 SAX 事件不能说 明其中的内容。
Simple API for XML(SAX)
一些常用的 SAX 事件
在基于 SAX 的应用程序中,多数时候您都要处理五种基本的事件。 startDocument() 告诉您解析器发现了文档的开始。该事件没有传递任何信息,只是告诉您解析
java实战之解析xml
java实战之解析xml 在java中解析xml有现成的包提供⽅法,常⽤的有四类:Dom,JDom,Sax以及Dom4j。
其中前者是java中⾃带的,后三者需要⼤家从开源诸如sourceforge这样的⽹站下载jar包,然后在eclipse中“build path”加载外来的jar⽂件就⾏。
各⾃的⼊门demo可以观看官⽹⽂档,听说⽂档有点晦涩难懂,可以多多google之,园⼦⾥有的是资源。
接下来主要讲的是如何使⽤Dom4j解析xml⽂档。
1、什么是xml ⾸先从维基百科⾥盗图⼀张,解释xml的主要结构——『节点(node):节点名称和节点值。
』,『属性(attribute):属性名称和属性值。
』。
上图中第⼀⾏解释了该xml⽂件的版本信息,这在写⼊xml⽂件的时候需要注明,有时候还需要注明⽂件的编码⽅式例如“utf-8”。
在每⼀个xml⽂件中都有⼀个根节点,所有节点数据都是包含在根节点中,例如本xml⽂档中的根节点名称为quiz。
quiz根节点下有⼀个名称为qanda⼦节点,这样类似的⼦节点是可重复的,当然在本xml⽂件中根节点下只有⼀个直系⼦节点qanda,qanda节点中有⼀个名称为seq的属性,其属性值为“1”,在qanda中有两个⼦节点,第⼀个⼦节点为question,该⼦节点的节点值为Who was the forty-second....⼀堆⽂字,符号标签</question>标志着该节点值的结束。
以此类推第⼆个⼦节点answer的节点值(节点内容)为William....,后⾯<!--....>⾥⾯的内容是注释,类似html⽂件中的注释信息。
对xml语⾔有更多兴趣的可去学习。
2、开始实战2.1 准备材料 以下是我的xml⽂档⽰例,⽬的是了解xml⽂档的结构(完整⽂档见): 上⾯的截图中,第⼀个⽂件ccms_position.xml⽂件就是传说中的标记语⾔,常⽤语web service中数据的传输,在eclipse中xml⽂件有两种展⽰⽅式(以上展⽰的是Source源⽂件模式),它为了让程序员⽅便的解析和编写xml⽂件特意设计的Design模式真的很⼈性化(⾃⾏在eclipse中打开xml⽂件就可以切换Design模式)。
java对XML文件的解析、节点的增加、删除操作总结
java对XML⽂件的解析、节点的增加、删除操作总结1、java代码:主要采⽤dom来进⾏操作复制代码代码如下:package test;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;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;import org.w3c.dom.Text;import org.xml.sax.SAXException;public class XmlOprate {Document doc;DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder;NodeList imags;String path;public NodeList getImags() {return imags;}public void setImags(NodeList imags) {this.imags = imags;}/*** 构造⽅法* @param path:xml⽂件的路径* @param nodes:要解析的xml节点名称*/public XmlOprate(String path) {super();this.path = path;System.out.println(System.getProperty("user.dir"));}/*** 解析XML* @param path*/public void readXml(){try {builder = factory.newDocumentBuilder();Document doc=builder.parse(path);doc.normalize();NodeList imags =doc.getElementsByTagName("imags");this.setImags(imags);for (int i=0;i<imags.getLength();i++){Element link=(Element) imags.item(i);System.out.print("title: ");System.out.println(link.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());System.out.print("URL: ");System.out.println(link.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());System.out.print("imgsrc: ");System.out.println(link.getElementsByTagName("imgsrc").item(0).getFirstChild().getNodeValue()); System.out.println();}}catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** addCode* @param path*/public void addXmlCode(String imgsrc,String title,String url){try {builder = factory.newDocumentBuilder();Document doc=builder.parse(path);doc.normalize();Text textseg;Element imag=doc.createElement("imags");Element linkimgsrc=doc.createElement("imgsrc");textseg=doc.createTextNode(imgsrc);linkimgsrc.appendChild(textseg);imag.appendChild(linkimgsrc);Element linktitle=doc.createElement("title");textseg=doc.createTextNode(title);linktitle.appendChild(textseg);imag.appendChild(linktitle);Element linkurl=doc.createElement("url");textseg=doc.createTextNode(url);linkurl.appendChild(textseg);imag.appendChild(linkurl);doc.getDocumentElement().appendChild(imag);TransformerFactory tFactory =TransformerFactory.newInstance();Transformer transformer;transformer = tFactory.newTransformer();DOMSource source = new DOMSource(doc);StreamResult result = new StreamResult(new java.io.File(path));transformer.transform(source, result);}catch(Exception e){}}/*** delete xml code* @param path*/public void delXmlCode(){try {builder = factory.newDocumentBuilder();doc=builder.parse(path);doc.normalize();NodeList imags =doc.getElementsByTagName("imags");Element elink=(Element) imags.item(0);elink.removeChild(elink.getElementsByTagName("imgsrc").item(0));elink.removeChild(elink.getElementsByTagName("title").item(0));elink.removeChild(elink.getElementsByTagName("url").item(0));doc.getFirstChild().removeChild(elink);TransformerFactory tFactory =TransformerFactory.newInstance();Transformer transformer = tFactory.newTransformer();DOMSource source = new DOMSource(doc);StreamResult result = new StreamResult(new java.io.File(path));transformer.transform(source, result);} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (TransformerConfigurationException e) {e.printStackTrace();} catch (TransformerException e) {e.printStackTrace();}}}2、xml部分复制代码代码如下:<?xml version="1.0" encoding="UTF-8" ?><root><imags><imgsrc>images/ad-01.jpg</imgsrc><title>胡志明市</title><url>/cn/journey/hochiminhcity/</url></imags><imags><imgsrc>images/ad-02.jpg</imgsrc><title>⾹港2</title><url>/cn/journey/hongkong/</url></imags></root>3、总结:看对xml操作的三个⽅法(读、写、删),他们的初始化语句都相同:复制代码代码如下:builder = factory.newDocumentBuilder();Document doc=builder.parse(path);doc.normalize();开始我打算把这部分相同的部分拿出来写在构造⽅法中,但是在测试中发现,这样总是会报空指针的错误(搞了我好久); ⽽只是把builder = factory.newDocumentBuilder();放到builder的初始化语句中的时候,读没问题,但是当写或者删的时候也会报错;所以就写成现在这样了,感觉有点乱乱的,但也没想到什么好的⽅法,就先贴到这⾥了,以后可能会⽤得着。
java解析xml
Java解析XML(4种方法)xml文件<?xml version="1.0" encoding="utf-8" ?> <class><student><firstname>cxx1</firstname><lastname>Bob1</lastname><nickname>stars1</nickname><marks>85</marks></student><student rollno="493"><firstname>cxx2</firstname><lastname>Bob2</lastname><nickname>stars2</nickname><marks>85</marks></student><student rollno="593"><firstname>cxx3</firstname><lastname>Bob3</lastname><nickname>stars3</nickname><marks>85</marks></student></class>1234567891011121314151617181920211.DOM方式package com.cxx.xml;import org.w3c.dom.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;/*** @Author: cxx* Dom操作xml* @Date: 2018/5/29 20:19*/public class DomDemo {//用Element方式public static void element(NodeList list){for (int i = 0; i <list.getLength() ; i++) {Element element = (Element) list.item(i);NodeList childNodes = element.getChildNodes();for (int j = 0; j <childNodes.getLength() ; j++) {if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {//获取节点System.out.print(childNodes.item(j).getNodeName() + ":");//获取节点值System.out.println(childNodes.item(j).getFirstChild().getNodeValue()) ;}}}}public static void node(NodeList list){for (int i = 0; i <list.getLength() ; i++) {Node node = list.item(i);NodeList childNodes = node.getChildNodes();for (int j = 0; j <childNodes.getLength() ; j++) {if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {System.out.print(childNodes.item(j).getNodeName() + ":");System.out.println(childNodes.item(j).getFirstChild().getNodeValue()) ;}}}}public static void main(String[] args) {//1.创建DocumentBuilderFactory对象DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();//2.创建DocumentBuilder对象try {DocumentBuilder builder = factory.newDocumentBuilder(); Document d = builder.parse("src/main/resources/demo.xml"); NodeList sList = d.getElementsByTagName("student");//element(sList);node(sList);} catch (Exception e) {e.printStackTrace();}}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455结果截图2.SAX方式package com.cxx.xml;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;/*** @Author: cxx* SAX解析DOM* 一行一行 Handler* startElement* endElement* @Date: 2018/5/29 20:03*/public class SaxDemo {public static void main(String[] args) throws Exception {//1.或去SAXParserFactory实例SAXParserFactory factory = SAXParserFactory.newInstance();//2.获取SAXparser实例SAXParser saxParser = factory.newSAXParser();//创建Handel对象SAXDemoHandel handel = new SAXDemoHandel();saxParser.parse("src/main/resources/demo.xml",handel);}}class SAXDemoHandel extends DefaultHandler {//遍历xml文件开始标签@Overridepublic void startDocument() throws SAXException {super.startDocument();System.out.println("sax解析开始");}//遍历xml文件结束标签@Overridepublic void endDocument() throws SAXException {super.endDocument();System.out.println("sax解析结束");}@Overridepublic void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {super.startElement(uri, localName, qName, attributes);if (qName.equals("student")){System.out.println("============开始遍历student=============");//System.out.println(attributes.getValue("rollno"));}else if (!qName.equals("student")&&!qName.equals("class")){ System.out.print("节点名称:"+qName+"----");}}@Overridepublic void endElement(String uri, String localName, String qName) throws SAXException {super.endElement(uri, localName, qName);if (qName.equals("student")){System.out.println(qName+"遍历结束");System.out.println("============结束遍历student=============");}}@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {super.characters(ch, start, length);String value = new String(ch,start,length).trim();if (!value.equals("")) {System.out.println(value);}}}1234567891011131415161718192021222324252627282930313233343536373839404142434445464748495051525354555758596061626364656667686970717273结果截图3.JDOM方式<!--jdom --><dependency><groupId>org.jdom</groupId><artifactId>jdom</artifactId><version>1.1.3</version></dependency>123456package com.cxx.xml;import org.jdom.Attribute;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder; import java.io.File;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream;import java.util.List;* @Author: cxx* JDom解析xml* 快速开发XML应用程序。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用SAX方式解析XML,XML文件如下:
<?xml version="1.0" encoding="gb2312"?>
<person>
<name>王小明</name>
<college>信息学院</college>
<telephone>6258113</telephone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</person>
事件回调类SAXHandler.java
import java.io.*;
import java.util.Hashtable;
import org.xml.sax.*;
public class SAXHandler extends HandlerBase
{
private Hashtable table = new Hashtable();
private String currentElement = null;
private String currentValue = null;
public void setTable(Hashtable table)
{
this.table = table;
}
public Hashtable getTable()
{
return table;
}
public void startElement(String tag, AttributeList attrs)
动力节点
throws SAXException
{
currentElement = tag;
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
currentValue = new String(ch, start, length);
}
public void endElement(String name) throws SAXException
{
if (currentElement.equals(name))
table.put(currentElement, currentValue);
}
}
JSP内容显示源码,SaxXml.jsp:
<HTML>
<HEAD>
<TITLE>剖析XML文件people.xml</TITLE>
</HEAD>
<BODY>
<%@ page errorPage="ErrPage.jsp"
contentType="text/html;charset=GB2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Hashtable" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="org.xml.sax.*" %>
动力节点
<%@ page import="javax.xml.parsers.SAXParserFactory" %>
<%@ page import="javax.xml.parsers.SAXParser" %>
<%@ page import="SAXHandler" %>
<%
File file = new File("c:\\people.xml");
FileReader reader = new FileReader(file);
Parser parser;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SAXHandler handler = new SAXHandler();
sp.parse(new InputSource(reader), handler);
Hashtable hashTable = handler.getTable();
out.println("<TABLE BORDER=2><CAPTION>教师信息表</CAPTION>");
out.println("<TR><TD>姓名</TD>" + "<TD>" +
(String)hashTable.get(new String("name")) + "</TD></TR>");
out.println("<TR><TD>学院</TD>" + "<TD>" +
(String)hashTable.get(new String("college"))+"</TD></TR>");
out.println("<TR><TD>电话</TD>" + "<TD>" +
(String)hashTable.get(new String("telephone")) + "</TD></TR>");
out.println("<TR><TD>备注</TD>" + "<TD>" +
(String)hashTable.get(new String("notes")) + "</TD></TR>");
out.println("</TABLE>");
%>
</BODY>
</HTML>
动力节点。