加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML解析

发布时间:2020-12-16 00:03:59 所属栏目:百科 来源:网络整理
导读:Dom解析 将整个文档加载到内存中,拿到了树状结构根节点相当于拿到了全部节点。 优点:方便的实现增加,修改,删除的操作。 缺点:一次在内存中分配一个树形结构,容易造成内存的溢出。 编程思路:DocumentBuilderFacory-DocumentBuilder-Document-NodeList-

Dom解析

将整个文档加载到内存中,拿到了树状结构根节点相当于拿到了全部节点。

优点:方便的实现增加,修改,删除的操作。

缺点:一次在内存中分配一个树形结构,容易造成内存的溢出。

编程思路:DocumentBuilderFacory->DocumentBuilder->Document->NodeList->Node

若是修改xml,则需注意应该把内存中的document实例化到文件中,否则硬盘上的文件没有发生变化。

修改思路:TransformerFactory->Transformer->transform(DOMSource,StreamResult); DOMSource是document根节点,StreamResult是文件。

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomParse {
	@Test
	public void domparse() throws ParserConfigurationException,SAXException,IOException
	{
		DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=builderFactory.newDocumentBuilder();
		Document document =builder.parse("book.xml");
		NodeList list=document.getElementsByTagName("Name");
		Node node=list.item(1);  //第二个节点
		String content=node.getTextContent();
		System.out.println(content);	
	}
	@Test
	public void domModify() throws ParserConfigurationException,IOException,TransformerException
	{
		DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=builderFactory.newDocumentBuilder();
		Document document =builder.parse("book.xml");
		NodeList list=document.getElementsByTagName("Name");
		Node node=list.item(1);  //第二个节点
		node.setTextContent("wanhao");
		
		TransformerFactory factory=TransformerFactory.newInstance();
		Transformer transformer=factory.newTransformer();
		Source xmlSource=new DOMSource(document);
		Result outputTarget=new StreamResult("book.xml");
		transformer.transform(xmlSource,outputTarget);
	}
}

book.xml放在项目根路径下

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AddressBook>
    <Address id="1" isLocal="true">
        <Name solutation="Mr.">Sam</Name>
        <Street>QuanKouRd.</Street>
        <City>ShangHai</City>
        <State>US</State>
        <Country>China</Country>
        <Pin>111</Pin>
    </Address>
    <Address id="2" isLocal="false">
        <Name solutation="Mrs.">wanhao</Name>
        <Street>JiaHangRd.</Street>
        <City>ShangHai</City>
        <State>US</State>
        <Country>India</Country>
        <Pin>222</Pin>
    </Address>
</AddressBook>

SAX解析

一个元素一个元素的解析,不会造成内存溢出,当然也不可以修改xml。

思路SAXParserFactory -> SAXParser ->parse ->匿名内部类DefaultHandler

@Test
		public void saxParse() throws ParserConfigurationException,IOException{
			SAXParserFactory parseFactory=SAXParserFactory.newInstance();
			SAXParser parser=parseFactory.newSAXParser();
			parser.parse(new File("book.xml"),new DefaultHandler(){

				@Override
				public void startDocument() throws SAXException {
					System.out.println("文档开始");
				}

				@Override
				public void endDocument() throws SAXException {
					System.out.println("文档结束");
				}
				//qName 标签名字 ,attributes属性值,虽不是list,也可以通过get方法遍历,开始一个标签
				@Override
				public void startElement(String uri,String localName,String qName,Attributes attributes)
						throws SAXException {
					System.out.print("<"+qName);
					for(int  i=0;i<attributes.getLength();++i)
					{
						System.out.print(" "+attributes.getQName(i)+"="+attributes.getValue(i));
					}
					System.out.print(">");
				}

				@Override
				public void endElement(String uri,String qName) throws SAXException {
					System.out.print("</"+qName+">");
				}
				//文本内容
				@Override
				public void characters(char[] ch,int start,int length) throws SAXException {
					String content=new String(ch,start,length);
					System.out.print(content);
				}
			});
		}
若要获得第二个标签名为Name的标签中的值,也十分简单。

一边用int记录是第几个标签名为Name的标签,一边读取文本内容。

	   private static int cur=0;
		@Test
		public void getSecondName() throws ParserConfigurationException,IOException
		{
			SAXParserFactory factory=SAXParserFactory.newInstance();
			SAXParser parser=factory.newSAXParser();
			parser.parse(new File("book.xml"),new DefaultHandler(){

				@Override
				public void startElement(String uri,Attributes attributes)
						throws SAXException {
					if("Name".equals(qName))
					{
						cur++;
					}
				}

				@Override
				public void characters(char[] ch,int length) throws SAXException {
					if(cur==2)
					{
						cur++;
						System.out.println("第二个Name标签中值为"+new String(ch,length));
					}
				}
			});
		}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读