第一种:DOM。
DOM的全称是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分析器还是有很广泛的使用价值的。
- importjava.io.File;
@H_403_22@
- importjavax.xml.parsers.DocumentBuilder;
- importjavax.xml.parsers.DocumentBuilderFactory;
- importorg.w3c.dom.Document;
- importorg.w3c.dom.Element;
- importorg.w3c.dom.NodeList;
- publicclassDomTest1
@H_403_22@ {
- publicstaticvoidmain(String[]args)throwsException
@H_403_22@
@H_403_22@ DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
- //System.out.println("classname:"+dbf.getClass().getName());
- //step2:获得具体的dom解析器
@H_403_22@ DocumentBuilderdb=dbf.newDocumentBuilder();
- //System.out.println("classname:"+db.getClass().getName());
- //step3:解析一个xml文档,获得Document对象(根结点)
@H_403_22@ Documentdocument=db.parse(newFile("candidate.xml"));
@H_403_22@ NodeListlist=document.getElementsByTagName("PERSON");
- for(inti=0;i<list.getLength();i++)
@H_403_22@ Elementelement=(Element)list.item(i);
@H_403_22@ Stringcontent=element.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue();
@H_403_22@ System.out.println("name:"+content);
@H_403_22@ content=element.getElementsByTagName("ADDRESS").item( System.out.println("address:"+content);
@H_403_22@ content=element.getElementsByTagName("TEL").item( System.out.println("tel:"+content);
@H_403_22@ content=element.getElementsByTagName("FAX").item( System.out.println("fax:"+content);
@H_403_22@ content=element.getElementsByTagName("EMAIL").item( System.out.println("email:"+content);
@H_403_22@ System.out.println("--------------------------------------");
@H_403_22@ }
@H_403_22@ }
importorg.w3c.dom.Attr;
importorg.w3c.dom.Comment;
importorg.w3c.dom.NamedNodeMap;
importorg.w3c.dom.Node;
/**
*使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上
*@authorzhanglong
*
*/
publicclassDomTest3
@H_
403_22@ Documentdoc=db.parse(
newFile("student.xml"));
//获得根元素结点
@H_
403_22@ Elementroot=doc.getDocumentElement();
@H_
403_22@ parseElement(root);
privatestaticvoidparseElement(Elementelement)
@H_
403_22@ StringtagName=element.getNodeName();
@H_
403_22@ NodeListchildren=element.getChildNodes();
@H_
403_22@ System.out.print(
"<"+tagName);
//element元素的所有属性所构成的NamedNodeMap对象,需要对其进行判断
@H_
403_22@ NamedNodeMapmap=element.getAttributes();
//如果该元素存在属性
if(null!=map)
0;i<map.getLength();i++)
//获得该元素的每一个属性
@H_
403_22@ Attrattr=(Attr)map.item(i);
@H_
403_22@ StringattrName=attr.getName();
@H_
403_22@ StringattrValue=attr.getValue();
@H_
403_22@ System.out.print(
""+attrName+"=\""+attrValue+"\"");
@H_
403_22@ System.out.print(
">");
0;i<children.getLength();i++)
@H_
403_22@ Nodenode=children.item(i);
//获得结点的类型
shortnodeType=node.getNodeType();
if(nodeType==Node.ELEMENT_NODE)
//是元素,继续递归
@H_
403_22@ parseElement((Element)node);
elseif(nodeType==Node.TEXT_NODE)
//递归出口
@H_
403_22@ System.out.print(node.getNodeValue());
elseif(nodeType==Node.COMMENT_NODE)
@H_
403_22@ System.out.print(
"<!--");
@H_
403_22@ Commentcomment=(Comment)node;
//注释内容
@H_
403_22@ Stringdata=comment.getData();
@H_
403_22@ System.out.print(data);
@H_
403_22@ System.out.print(
"-->");
@H_
403_22@ System.out.print(
"</"+tagName+">");
@H_
403_22@ }
sax:SAX的全称是Simple APIs for XML,也即XML简单应用程序接口。与DOM不同,SAX提供的访问模式是一种顺序模式,这是一种快速读写XML数据的方式。当使用SAX分析器对 XML文档进行分析时,会触发一系列事件,并激活相应的事件处理函数,应用程序通过这些事件处理函数实现对XML文档的访问,因而SAX接口也被称作事件 驱动接口。
importjavax.xml.parsers.SAXParser;
importjavax.xml.parsers.SAXParserFactory;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
publicclassSaxTest1
//step1:获得SAX解析器工厂实例
@H_
403_22@ SAXParserFactoryfactory=SAXParserFactory.newInstance();
//step2:获得SAX解析器实例
@H_
403_22@ SAXParserparser=factory.newSAXParser();
//step3:开始进行解析
@H_
403_22@ parser.parse(
newFile("student.xml"),newMyHandler());
classMyHandlerextendsDefaultHandler
@H_
403_22@
@Override
publicvoidstartDocument()throwsSAXException
@H_
403_22@ System.out.println(
"parsebegan");
publicvoidendDocument()throwsSAXException
@H_
403_22@ System.out.println(
"parsefinished");
publicvoidstartElement(Stringuri,StringlocalName,StringqName,
@H_
403_22@ Attributesattributes)
throwsSAXException
@H_
403_22@ System.out.println(
"startelement");
publicvoidendElement(Stringuri,StringqName)
@H_
403_22@ System.out.println(
"finishelement");
@H_
403_22@ }
importjava.util.Stack;
publicclassSaxTest2
newMyHandler2());
classMyHandler2extendsDefaultHandler
privateStack<String>stack=newStack<String>();
privateStringname;
privateStringgender;
privateStringage;
@H_
403_22@ stack.push(qName);
0;i<attributes.getLength();i++)
@H_
403_22@ StringattrName=attributes.getQName(i);
@H_
403_22@ StringattrValue=attributes.getValue(i);
@H_
403_22@ System.out.println(attrName+
"="+attrValue);
publicvoidcharacters(char[]ch,intstart,intlength)
@H_
403_22@ Stringtag=stack.peek();
if("姓名".equals(tag))
@H_
403_22@ name=
newString(ch,start,length);
elseif("性别".equals(tag))
@H_
403_22@ gender=
elseif("年龄".equals(tag))
@H_
403_22@ age=@H_493_
502@ stack.pop();
if("学生".equals(qName))
@H_
403_22@ System.out.println(
"姓名:"+name);
@H_
403_22@ System.out.println(
"性别:"+gender);
@H_
403_22@ System.out.println(
"年龄:"+age);
@H_
403_22@ System.out.println();
@H_
403_22@ }
JDOM:
JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。(http://jdom.org)
•JDOM 直接为JAVA编程服务。它利用更为强有力的JAVA语言的诸多特性(方法重载、集合概念等),把SAX和DOM的功能有效地结合起来。
•JDOM是用Java语言读、写、操作XML的新API函数。在直接、简单和高效的前提下,这些API函数被最大限度的优化。
jdom创建xml
importjava.io.FileWriter;
importorg.jdom.Attribute;
importorg.jdom.Comment;
importorg.jdom.Document;
importorg.jdom.Element;
importorg.jdom.output.Format;
importorg.jdom.output.XMLOutputter;
publicclassJDomTest1
@H_
403_22@ Documentdocument=
newDocument();
@H_
403_22@ Elementroot=
newElement("root");
@H_
403_22@ document.addContent(root);
@H_
403_22@ Commentcomment=
newComment("Thisismycomments");
@H_
403_22@ root.addContent(comment);
@H_
403_22@ Elemente=
newElement("hello");
@H_
403_22@ e.setAttribute(
"sohu","www.sohu.com");
@H_
403_22@ root.addContent(e);
@H_
403_22@ Elemente2=
newElement("world");
@H_
403_22@ Attributeattr=
newAttribute("test","hehe");
@H_
403_22@ e2.setAttribute(attr);
@H_
403_22@ e.addContent(e2);
@H_
403_22@ e2.addContent(
newElement("aaa").setAttribute("a","b")
@H_
403_22@ .setAttribute(
"x","y").setAttribute("gg","hh").setText("textcontent"));
@H_
403_22@ Formatformat=Format.getPrettyFormat();
@H_
403_22@ format.setIndent(
"");
//format.setEncoding("gbk");
@H_
403_22@ XMLOutputterout=
newXMLOutputter(format);
@H_
403_22@ out.output(document,153); font-weight:bold; background-color:inherit">newFileWriter(
"jdom.xml"));
@H_
403_22@ }
JDOM解析xml
importjava.io.FileOutputStream;
importjava.util.List;
importorg.jdom.input.SAXBuilder;
publicclassJDomTest2
@H_
403_22@ SAXBuilderbuilder=
newSAXBuilder();
@H_
403_22@ Documentdoc=builder.build(
newFile("jdom.xml"));
@H_
403_22@ Elementelement=doc.getRootElement();
@H_
403_22@ System.out.println(element.getName());
@H_
403_22@ Elementhello=element.getChild(
"hello");
@H_
403_22@ System.out.println(hello.getText());
@H_
403_22@ Listlist=hello.getAttributes();
0;i<list.size();i++)
@H_
403_22@ Attributeattr=(Attribute)list.get(i);
@H_
403_22@ hello.removeChild(
"world");
newXMLOutputter(Format.getPrettyFormat().setIndent(""));
@H_
403_22@ out.output(doc,153); font-weight:bold; background-color:inherit">newFileOutputStream(
"jdom2.xml"));
@H_
403_22@ }
Dom4j
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.XMLWriter;
publicclassTest1
//创建文档并设置文档的根元素节点:第一种方式
//Documentdocument=DocumentHelper.createDocument();
//
//Elementroot=DocumentHelper.createElement("student");
//document.setRootElement(root);
//创建文档并设置文档的根元素节点:第二种方式
@H_
403_22@ Elementroot=DocumentHelper.createElement(
"student");
@H_
403_22@ Documentdocument=DocumentHelper.createDocument(root);
@H_
403_22@ root.addAttribute(
"name","zhangsan");
@H_
403_22@ ElementhelloElement=root.addElement(
"hello");
@H_
403_22@ ElementworldElement=root.addElement(
"world");
@H_
403_22@ helloElement.setText(
"hello");
@H_
403_22@ worldElement.setText(
"world");
@H_
403_22@ helloElement.addAttribute(
"age","20");
@H_
403_22@ XMLWriterxmlWriter=
newXMLWriter();
@H_
403_22@ xmlWriter.write(document);
@H_
403_22@ OutputFormatformat=
newOutputFormat("",153); background-color:inherit">true);
@H_
403_22@ XMLWriterxmlWriter2=
newXMLWriter(newFileOutputStream("student2.xml"),format);
@H_
403_22@ xmlWriter2.write(document);
@H_
403_22@ XMLWriterxmlWriter3=
newXMLWriter(newFileWriter("student3.xml"),248)"> xmlWriter3.write(document);
@H_403_22@ xmlWriter3.close();
importjava.util.Iterator;
importorg.dom4j.io.DOMReader;
importorg.dom4j.io.SAXReader;
publicclassTest2
@H_
403_22@ SAXReadersaxReader=
newSAXReader();
@H_
403_22@ Documentdoc=saxReader.read(
newFile("student2.xml"));
@H_
403_22@ Elementroot=doc.getRootElement();
@H_
403_22@ System.out.println(
"rootelement:"+root.getName());
@H_
403_22@ ListchildList=root.elements();
@H_
403_22@ System.out.println(childList.size());
@H_
403_22@ ListchildList2=root.elements(
"hello");
@H_
403_22@ System.out.println(childList2.size());
@H_
403_22@ Elementfirst=root.element(
"hello");
@H_
403_22@ System.out.println(first.attributeValue(
"age"));
for(Iteratoriter=root.elementIterator();iter.hasNext();)
@H_
403_22@ Elemente=(Element)iter.next();
@H_
403_22@ System.out.println(e.attributeValue(
"age"));
@H_
403_22@ System.out.println(
"---------------------------");
@H_
403_22@ org.w3c.dom.Documentdocument=db.parse(@H_493_
502@ DOMReaderdomReader=
newDOMReader();
//将JAXP的Document转换为dom4j的Document
@H_
403_22@ Documentd=domReader.read(document);
@H_
403_22@ ElementrootElement=d.getRootElement();
@H_
403_22@ System.out.println(rootElement.getName());
publicclassTest3
newElement("联系人列表").setAttribute(newAttribute("公司",
@H_
403_22@
"A集团"));
@H_
403_22@ ElementcontactPerson=
newElement("联系人");
@H_
403_22@ root.addContent(contactPerson);
@H_
403_22@ contactPerson
@H_
403_22@ .addContent(
newElement("姓名").setText("张三"))
newElement("公司").setText("A公司"))
newElement("电话").setText("021-55556666"))
@H_
403_22@ .addContent(
newElement("地址")
newElement("街道").setText("5街"))
newElement("城市").setText("上海"))
newElement("省份").setText("上海市")));
@H_
403_22@ XMLOutputteroutput=
newXMLOutputter(Format.getPrettyFormat()
@H_
403_22@ .setIndent(
"").setEncoding("gbk"));
@H_
403_22@ output.output(document,153); font-weight:bold; background-color:inherit">newFileWriter(
"contact.xml"));
@H_
403_22@ }
@H_
403_22@ }