JDK提供的XML解析方式分为两种:DOM方式和SAX方式
DOM:Document Object Model。需要读取整个XML文档,先需要在内存中构架代表整个DOM树的Document对象,可以进行随机访问. 需要考虑内存.适合增删改
SAX:Simple API for XML。采用事件驱动的方式解析XML文件,边读边对文档进行处理.适合读取

其他的xml解析包:Dom4J, PullParser(安卓)

Dom4J实现类似SAX方式, API类似DOM方式

DOM @JDK

public class DomTest {

    // 解析xml获取document对象
private Document getDocument() throws ParserConfigurationException,
SAXException, IOException {
// 1. 获得工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 2. 获得 builder对象
DocumentBuilder builder = factory.newDocumentBuilder();
// 3. 解析xml得带document对象
Document document = builder.parse("src/book.xml");
return document;
} // 将内存中的document对象写回xml文件中
private void writeBack2Xml(Document document)
throws TransformerFactoryConfigurationError,
TransformerConfigurationException, TransformerException { TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult("src/book.xml"));
} // 读取节点文本
@Test
public void testReadContent() throws Exception{
Document document = getDocument();
//根据标签名获得节点列表
NodeList nodeList = document.getElementsByTagName("书");
System.out.println("长度 : " + nodeList.getLength());
// 返回第一个节点
Node firstNode = nodeList.item(0);
// 返回文本内容
String result = firstNode.getTextContent();
System.out.println(result);
} // 读取节点的属性值
@Test
public void testReadAttribute() throws Exception{
Document document = getDocument();
NodeList nodeList = document.getElementsByTagName("书");
// 确认本Node为元素节点后加强转
Node node = nodeList.item(0);
if (node instanceof Element) {
Element firstElement = (Element) node;
String result = firstElement.getAttribute("出版社");
System.out.println(result);
}
} // 添加节点
@Test
public void testAddPrice() throws Exception, SAXException, IOException{
Document document = getDocument();
Node firstNode = document.getElementsByTagName("书").item(0);
Element newElement = document.createElement("售价");
newElement.setTextContent("79.00元");
firstNode.appendChild(newElement);
writeBack2Xml(document); //写回
} // 删除节点
@Test
public void testDelete() throws Exception, SAXException, IOException{
Document document = getDocument();
NodeList priceNodeList = document.getElementsByTagName("售价");
for (int i = 0; i < priceNodeList.getLength(); i++) {
Node node = priceNodeList.item(i);
if("39.00元".equals(node.getTextContent())){
// 从父节点删除子节点, 类似dom的api
node.getParentNode().removeChild(node);
}
}
writeBack2Xml(document);
} // 打印所有元素节点的名称
@Test
public void testPrintAllElementsName() throws Exception, SAXException, IOException{
Document document = getDocument();
// 递归打印
printAllElementsName(document);
} public void printAllElementsName(Node node){
// 打印本节点
if(Node.ELEMENT_NODE==node.getNodeType()){
System.out.println(node.getNodeName());
}
// 处理子节点
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) { //递归出口: 循环完成
Node item = childNodes.item(i);
printAllElementsName(item);
}
}
}

SAX @JDK

public class SaxTest {

    public static void main(String[] args) throws Exception, SAXException {

        SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new MyDefaultHandler());
reader.parse("src/book.xml");
}
} class MyDefaultHandler extends DefaultHandler { // 作为被调用方, 流程不是这边控制, 所以定义状态位或计数器来标记流程进行的位置
private boolean isPrice = false;
private int count =1; @Override
public void startElement(String uri, String localName, String qName, // qName标签名
Attributes attributes) throws SAXException {
if ("售价".equals(qName)) {
isPrice = true;
count++;
}
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("售价".equals(qName)) {
isPrice = false;
}
} // 读到文本了
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (isPrice&&count==3) {
System.out.println("文本: " + new String(ch, start, length));
}
}
}

Dom4J

public class Dom4JTest {

    private Document getDocument() throws DocumentException {
// 获得 代表 xml 文件的 document 对象
SAXReader reader = new SAXReader();
Document document = reader.read("src/book.xml");
return document;
} private void wirteBack2Xml(Document document) throws UnsupportedEncodingException, FileNotFoundException, IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"), format);
writer.write(document);
writer.close();
} // 读取节点的文本内容
// 由于 dom4j采用sax方式去解析的xml文档, 所以dom4j不能直接获得深层次的某个节点, 需要一级级获得
@Test
public void testReadContent() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement();
Element firstLevelElement = rootElement.element("ele1");
Element secondLevelElement = firstLevelElement.element("ele2"); String value = secondLevelElement.getText();
System.out.println(value);
} // 读取属性值
@Test
public void testReadAttribute() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement(); List<Element> list = rootElement.elements("书");
Element secondElement = list.get(1);
Attribute attribute = secondElement.attribute("出版社"); String value = attribute.getValue();
System.out.println(value);
} // 添加节点
@Test
public void testAddPrice() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement();
Element secondBookElement = (Element) rootElement.elements("书").get(1);
// 创建新节点
secondBookElement.addElement("newEle").setText("this is new Element"); wirteBack2Xml(document);
} // 删除节点
@Test
public void testDeletePrice() throws Exception{ Document document = getDocument();
Element rootElement = document.getRootElement();
Element secondBookElement = (Element) rootElement.elements("书").get(1);
Element targetBookPrice = (Element) secondBookElement.elements("售价").get(0); // 拿到父节点, 然后删除这个子节点
targetBookPrice.getParent().remove(targetBookPrice);
wirteBack2Xml(document);
}
}

XML的两种解析方式的更多相关文章

  1. xml中俩种解析方式

    两种解析方式 1.from xml.etree import ElementTree as ET 利用ElementTree模块下的xml方法可以把一个字符串类型的东西转换成Element类,从而利用 ...

  2. xml常用四种解析方式优缺点的分析×××××

    xml常用四种解析方式优缺点的分析 博客分类: xml   最近用得到xml的解析方式,于是就翻了翻自己的笔记同时从网上查找了资料,自己在前人的基础上总结了下,贴出来大家分享下. 首先介绍一下xml语 ...

  3. XML 的4种解析方式

    在上一篇博客中,我们介绍了什么是 XML ,http://www.cnblogs.com/ysocean/p/6901008.html,那么这一篇博客我们介绍如何来解析 XML . 部分文档引用:ht ...

  4. Android平台中实现对XML的三种解析方式

    本文介绍在Android平台中实现对XML的三种解析方式. XML在各种开发中都广泛应用,Android也不例外.作为承载数据的一个重要角色,如何读写XML成为Android开发中一项重要的技能. 在 ...

  5. Javaweb学习笔记——(六)——————xml中jaxp两种解析方式和dom4j运用

    1.xml的scheam约束 dtd的语法:<!ElEMENT 元素名称 约束> **schema符合xml的语法,xml语句 **一个xml中可以有多个schema,多个schema使用 ...

  6. XML解析——Java中XML的四种解析方式

    XML是一种通用的数据交换格式,它的平台无关性.语言无关性.系统无关性.给数据集成与交互带来了极大的方便.XML在不同的语言环境中解析方式都是一样的,只不过实现的语法不同而已. XML的解析方式分为四 ...

  7. XML解析——Java中XML的四种解析方式(转载 by 龍清扬)

    XML是一种通用的数据交换格式,它的平台无关性.语言无关性.系统无关性.给数据集成与交互带来了极大的方便.XML在不同的语言环境中解析方式都是一样的,只不过实现的语法不同而已. XML的解析方式分为四 ...

  8. xml的四种解析方式(转载)

    众所周知,现在解析XML的方法越来越多,但主流的方法也就四种,即:DOM.SAX.JDOM和DOM4J 下面首先给出这四种方法的jar包下载地址 DOM:在现在的Java JDK里都自带了,在xml- ...

  9. C#读写XML的两种一般方式

    针对XML文档的应用编程接口中,一般有两种模型:W3C制定的DOM(Document Object Method,文档对象模型)和流模型. 流模型的两种变体:"推"模型(XML的简 ...

随机推荐

  1. Python(数据库之约束表的关系)

    一.约束 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性 主要分为: RIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KEY ...

  2. 配置 Docker 镜像下载的本地 mirror 服务

    Docker registry 工具如今已经非常好的支持了 mirror 功能,使用它能够配置一个本地的 mirror 服务.将 pull 过的镜像 cache 在本地.这样其他主机再次 pull 的 ...

  3. 自定义ActionBar图标

    <style name="Theme.glTheme" parent="android:Theme.Holo"> <item name=&qu ...

  4. Hibernate简单配置

    1.配置构建路径,加载用户库,hibernate4.3.8 MySQL-Driver 2.写User.java      纯POJO+持久化注解=PO @Entity @Table(name=&quo ...

  5. mac截屏

    shift+command+3 : 截全屏 shift+command+4 : 出现十字架的坐标图标,画框截图

  6. delphi webbrowser 获取iframe

    procedure TForm1.Button4Click(Sender: TObject);var Index: Integer; Document: IHTMLDocument2; FrameId ...

  7. Spring.Net+NHibernate+Castle学习网站

    1.刘冬  http://www.cnblogs.com/GoodHelper/archive/2009/10/16/1584243.html 2.学习资料 http://www.cnblogs.co ...

  8. 28. Implement strStr()(KMP字符串匹配算法)

    Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle ...

  9. Divide by Zero 2017 and Codeforces Round #399 (Div. 1 + Div. 2, combined) A. Oath of the Night's Watch

    地址:http://codeforces.com/problemset/problem/768/A 题目: A. Oath of the Night's Watch time limit per te ...

  10. [HEOI2016/TJOI2016]求和(第二类斯特林数)

    题目 [HEOI2016/TJOI2016]求和 关于斯特林数与反演的更多姿势\(\Longrightarrow\)点这里 做法 \[\begin{aligned}\\ Ans&=\sum\l ...