java解析xml-java开发java经验技巧

java解析xml-java开发java经验技巧

ID:30777802

大小:258.96 KB

页数:20页

时间:2019-01-03

上传者:U-991
java解析xml-java开发java经验技巧_第1页
java解析xml-java开发java经验技巧_第2页
java解析xml-java开发java经验技巧_第3页
java解析xml-java开发java经验技巧_第4页
java解析xml-java开发java经验技巧_第5页
资源描述:

《java解析xml-java开发java经验技巧》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

Java解析XML-编程开发技术Java解析XML原文出处:翡青XML解析技术有两种DOMSAX•DOM方式根据XML的层级结构在内存屮分配一个树形结构,把XML的标签,屈性和文本等元素都封装成树的节点对彖•优点:便于实现增删改查•缺点:XML文件过人可能造成内存溢出•SAX方式采用事件驱动模型边读边解析:从上到下一行行解析,解析到某一元素,调用相应解析方法•优点:不会造成内存溢出,•缺点:查询不方便,但不能实现增删改不同的公司和组织提供了针对DOM和SAX两种方式的解析器•SUN的jaxp•Dom4j组织的dom4j(最常用:如Spring)•JDom组织的jdom关于这三种解析器渊源口J以参考九腹解析xml文件四种方式.JAXP解析JAXP是JavaSE的一部分,在javax.xml.parsers包F,分别针对dom与sax提供了如下解析器:Dom•DocumentBuilder•DocumentBuilderFactorySAX SAXParser 示例XML如下,下面我们会使用JAXP对他进行增删改查操作•configAml•constraint.dtdJAXP-Dom/***@authorjifang*@since16/1/13下午11:24.*/publicclassXmlRead{©Testpublicvoidclient()throwsParserConfigurationException,IOException, SAXException{//生成一个Dom解析器 DocumentBuilderbuilder=DocumentBuilderFactory.newlnstance().newDocumentBuilder();//解析XML文件Documentdocument二builder,parse(ClassLoadcr.gctSystcmRcsourccAsStrcom("config,xml"));〃…}}DocumentBu订der的parse(String/File/InputSource/InputStreeinipcircim)方法可以将一个XML文件解析为一个Document对彖,代表整个文档.Document(org.w3c.dom包下)是一个接口,-其父接口为Node,Node的其他子接口还有ElementAttrText等.•NodeNode常用方法释义NodeappendChild(NodeAddsthenodenewChildtotheendofthelistofchildrenofnewChild)thisnode.NoderemoveChi1d(NodeRemovesthechildnodeindicatedbyoldChildfromthelistofoldChild)NodeListgetCh订dNodes()NamedNodeMapgetAttributes()children,andreturnsit.ANodeListthatcontainsallchildrenofthisnode・ANamedNodeMapcontainingtheattributesofthisnode(ifitisanElement)ornullotherwise・StringgetTextContent()Thisattributereturnsthetextcontentofthisnodeanditsdescendants・•Document释义Document常用方法ElementtagXame)createElement(String…•严.Createsanelementofthetypespecified・ReturnsaNodeListofalltheElementsindocumentorderwithagiventagnameandarecontainedinthedocument.TextcreateTextNode(Stringdata)CreatesaTextnodegiventhespecifiedstring.AttrcreateAttribute(Stringneime)CreatesanAttrofthegivenname.NodeListgetElementsByTaghnie(Stringtagnamc)Dom查询解析<bean/>标签上的所有属性publicclassXmlRcad{ privateDocumentdocument;©BeforepublicvoidsetUp()throwsParserConfigurationException,IOException,SAXException{document二DocumentBuildcrFactory.ncwlnstancc()・ncwDocumentBuilder()•parse(ClassLoader.getSystemResourceAsStream(z,config.xmlzz));}@Testpublicvoidclient()tbrowsParserConfigurationException,TOException,SAXExccption{NodeListbeans=document.getElementsByTagName(z,bean,z);for(inti=0;i%s%attribute.gctNameO,attribute.getValue());//System.out.printin(attribute.getNodeMine()+"->〃+attribute.getTextContent());•打印XML文件所冇标签名@Testpublicvoidclicnt(){list(document,0);}privatevoidlist(Nodenode,intdepth){if(node.getNodeType()二二Node.ELEME7T_N0DE){for(inti=0;i“);}NodeListchildNodes=node.getChi1dNodes();for(inti=0;i〈propertyname=,,namez,value二〃simple-bean〃>新添加I的〈/property>/***@authorjifang*@since16/1/17下午5:56.*/publicclassXmlAppend{//文档回写器privateTransfonncrtransfonncr;//xml文档privateDocumentdocument;©BeforepublicvoidsetUp()throwsParserConfigurationException,TOException,SAXExccption{document=DocumentBuiIderFactory.newlnstance().newDocumentBuiIder()*parse(ClassLoader.getSystemResourceAsStream(/zconfig.xinl〃));}@Testpublicvoidclicnt(){//得到第一bean标签NodefirstBean二document.getElementsByTagName(/zbean/z).item(O);/**创建一个property标签**/Elementproperty=document.createElement("property〃);//为property标签添加属性//property.setAttribute(z,name,/,〃name〃);//property.setAttribute(/zvalue/z,〃feiqing〃);Attrname二document.createAttribute(〃name〃);name.setValue(ame/z);property.setAttributcNodc(namc);Attrvalue=document.createAttribute(z,valuez,);value.setValue(/zsimple-bean/z);property.setAttributeNode(value);//为property标签添加内容//property.setTextContent(z,新添加的〃);property.appendChild(document.createTextNode(〃新添力|丨的〃));//将property标签添加到bean标签下firstBean.appendChi1d(property);}@AfterpublicvoidtearDownOthrowsTransformerException{transformer二TransformerFactory.newlnstance().newTransformer();//写回XML transformer,transform(newDOMSource(document),newStrcamRcsult(,zsrc/main/resources/config,xml"));}}注意:必须将内存中的DOM写回XML文档才能生效Dom更新节点•将刚刚添加的修改如下〈propertyname二〃name"value二〃new-simple-bearT>simple-bean是新添力口的@Testpublicvoidclient(){NodcListproperties=document,gctElemcntsByTagNanic(''property〃);for(inti=0;i标签@Testpublicvoidclient(){NodeListproperties二document.getElementsByTagName("property");for(inti=0;i〈properties.getLengthO;++i){Elementproperty=(Element)properties,item(i);if(property.getAttribute(〃value〃).equals(/znew-simple-bean/z)){property.getParentNode().removeChild(property);break;JAXP-SAXSAXParser实例需要从SAXParserFactory实例的newSAXParser()方法获得,用于解析XML文件的parse(Stringuri,DefaultHandlerdh)方法没有返回值,但比DOM方法多了一个事件处理器参数DefaultHandler: •解析到开始标签上I动调用DefaultHandler的startElement()方法;•解析到标签内容(文本),自动调用DefaultHandler的characters()方法;•解析到结束标签,口动调用DefaultHandler的endElement()方法.Sax查询•打印整个XML文档/***@authorjifang*©since16/1/17下午9:16.*/publicclassSaxRead{@Testpublicvoidclicnt()throwsParscrConfigurationExccption,IOExccption,SAXException{SAXParserparser二SAXParserFactory.newlnstance().newSAXParser();parser,parse(ClassLoader.getSystemResourceAsStream(/zconfig.xml/z),newSaxHandler());}privateclassSaxHandlerextendsDefaultHandler{©OverridepublicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)tbrowsSAXException{System,out.print("〈“+qNamc);for(inti=0;i〃);}©Overridepublicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{System,out.print(newString(ch,start,length));}©OverridepublicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{System,out.prin+qName+〃>“);•打印所有property标签内容的Handler privateclassSaxHandlerextendsDefaultHandler{//用互斥锁保护isProperty变量privatebooleanisProperty=false;privateLockmutex二newRccntremtLock();©OverridepublicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)throwsSAXException{if(qName.equals("property")){mutex,lock();isProperty=true;}}©Overridepublicvoidcharacters(chart]ch,intstart,intlength)throwsSAXException{//只有被锁定之后才有可能是trueif(isProperty){System.out.println(newString(ch,start,length));}}©OverridepublicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{if(qName.equals("property")){try{isProperty=false;}finally{mutex.unlock();注:SAX方式不能实现增删改操作.Dom4j解析Dom4j是JDom的一种智能分支,从原先的JDom组织中分离出來,提供了比JDom功能更加强大,性能更加卓越的Dom4j解析器(比如捉供对XPath支持).使用Dom4j需要在pom中添加如下依赖:dom4jdom4jl.6.l〈/dependency〉示例XML如下,下面我们会使用Domdj对他进行增删改查操作:config.xml •context.xsd〈complcxTypc>〈attributename二〃name"type二〃string"use=,,requiredz,/>/***@authorjifang*@since16/1/18下午4:02.*/ publicclassDom4jRead{@Tcstpublicvoidclient()throwsDocumentException{SAXReaderreader二newSAXReader();Documentdocument二reader,read(ClassLoader.£etSystemResource(〃configxmlz/));〃…与JAXP类似Document也是一个接口(org.dom4j包下),其父接口是Node,Node的子接口还有ElementAttributeDocumentTextCDATABranch等•NodeNode常用方法释义ElementgetParent()getParentreturnstheparentElementifthisnodesupportstheparentrelationshipornullifitistherootelementordoesnotsupporttheparentrelationship. •DocumentDocument常用方法释义ElementgetRootElement()ReturnstherootElementforthisdocument.•ElementElement常用方法voidadd(Attribute/Textparam)ElemcntaddAttributc(Stringname,Stringvalue)Attributeattribute(intindex)释义AddsthegivenAttribute/Texttothiselement.Addstheattributevalueofthegivenlocalname・ReturnstheattributeatthespecifiedindexGetsthenameAttribliteattribute(Stringname)ReturnstheattributewiththegivenElementelement(Stringname)IteratorelementTterator()IteratorelementIterator(Stringname)Listelements()Listelements(Stringname)Returnsthefirstelementforthegivenlocalnameandanynamespace・Returnsaniteratoroverallthiselementschildelements.Returnsaniteratorovertheelementscontainedinthiselementwhichmatchthegivenlocalnameandanynamespace.Returnstheelementscontainedinthiselement.Returnstheelementscontainedinthiselementwiththegivenlocalnameandanynamespace・•BranchBranch常用方法释义ElementaddElement(StringAddsanewElementnodewiththegivennametothisbranchname)andreturnsareferencetothenewnode・/、RemovesthegivenNodeifthenodeisanimmediatechildofbooleanremove(Nodenode;「..thisbranch.Dom4j查询•打印所有属性信息:/***@authorjifang*©since16/1/18下午4:02.*/ publicclassDomdjRead{privateDocumentdocument;@BcforcpublicvoidsetUp()throwsDocumentException{document二newSAXReader()•read(ClassLoader.getSystemResource(/zconfig.xml〃));}@Tcst@SuppressWarnings(''unchecked'7)publicvoidclient(){Elementbeans二document.getRootElement();for(Iteratoriterator=beans,elementIterator();iterator.hasNext();){Elementbean=(Element)iterator.next();Stringid=bean.attributeValue(z/idz/);Stringclazz二bean.attributeValue(〃class〃);System,out.printin(z/id:〃+id+"、class:"+clazz);seanPropcrtics(bcon.clcmcnts());}}publicvoidscanProperties(Listproperties){for(Elementproperty:properties){System,out.print(〃namc:"+property,attributcValuc(〃namcz,));Attributevalue=property,attribute("value");if(value!=null){System,out.pr〃+value.getName()+〃:+value.getValueO);}Attributeref二property.attribute(〃rcf〃);if(ref!=null){System,out.printing〃+ref.getName()+〃:+ref.getValue());}}}}Dom4j添加节点在第一个标签末尾添加标签新添加的标签/** *©authorjifang*@since16/1/19±午9:50.*/publicclassDom4jAppcnd{//...©Testpublicvoiddient(){Elementbeans=document.getRootElement();ElcmentfirstBcan二boans.clcmcnt(〃bcan〃);Elementproperty二firstBean.addElement("property");property.addAttribute(/zname/z,/zrefBean/z);property.addAttribute(,zref,z,〃id2〃);property.setText(z/新添加的标签〃);IJ@AfterpublicvoidtearDown()throwsIOException{//回写XMLOutputFormatformat=OutputFormat.createPrettyPrint();XMLWritcrwriter二newXMLWritcr(newFileOutputStream(z,src/main/resources/config.format);writer,write(document);}}我们可以将获取读写XML操作封装成一个工具,以后调用时会方便些:/***©authorjifang*@since16/1/19下午2:12.*/publicclassXmlUtils{publicstaticDocumentgetXmlDocument(Stringconfig){try{returnnewSAXReaderO.read(ClassLoader.getSystemResource(config));}catch(DocumentExceptione){thrownewRuntimcExccption(c);}}publicstaticvoidwriteXmlDocument(Stringpath,Documentdocument)try{newXMLWritcr(newFilcOutputStrcom(p3th),OutputFormat・createPrettyPrint())•write(document);}catch(IOExceptione){thrownewRuntimeException(e);}}} 在第一个的第一个后而添加一个标签新添加的标签publicclassDom4jAppend{privateDocumentdocument;©BeforepublicvoidsetUp(){document二XmlUtils.gctXmlDocumcnt("config.xml");}©Test©SuppressWarnings(〃unchecked")publicvoidclient(){Elcmentboans二documcnt.gctRootElcmcnt();ElementfirstBean=beans,element(z,bean,z);Listproperties=firstBean.elements();//Elementproperty二DocumentHelper//•createElement(QMeime.get("property",firstBcon.getNamcspaccURI()));Elementproperty二DocumentFactory.getlnstance()•createElement("property",firstBean.getNamespaceURI());property.addAttribute(/zname/z,〃:rate");property.eiddAttribute("value",〃3.14〃);properties.add(l,property);}©AfterpublicvoidtearDown(){XmlUtils.writeXmlDocument("sre/main/resources/config.xml"、document);}}Dom4j修改节点将idlbean的第一个〈property/〉修改如下:@Test©SuppressWarnings("unchecked")publicvoidclient(){Elementbeans=document.getRootElement();ElcmentfirstBcan二boans.clcmcnt(〃bcan〃);Listproperties=firstBean.elements();Elementproperty二DocumentFactory.getlnstance()•createElement(“property”,firstBean.getNamespaceURI());property.addAttribute(ame,z,〃rate〃); property・addAttributc("value","3・14");properties.add(l,property);}Dom4j删除节点删除刚刚修改的节点@Tcst@SuppressWarnings("uncheckecT)publicvoiddelete(){Listbeans二document.getRootElement().elements(〃bean〃);for(Elementbean:beans){if(bean.attributcValuc(^id^)・equals("idl")){Listproperties=bean,elements('"property〃);for(Elementproperty:properties){if(property.attributeValue(/zname/z).equals(ame/z)){//执行删除动作property.gctParcnt().remove(property);break;}}break;}Dom4j实例在Java反射一文中我们实现了根据JSON配置文件來加载bean的对象池,现在我们可以为其添加根据XML配置(XML文件同丽):/***©authorjifang*©since16/1/18下午9:18.*/publicclassXmlParse{privatestaticfinalObjectPoolPOOL=ObjectPoolBuilder.init(null);publicstaticElementparseBeans(Stringconfig){try{rcturnnewSAXReader().read(ClassLoader.getSystemResource(config)).getRootElemen10;}catch(DocumentExceptione){thrownewRuntimeException(e);ij }publicstaticvoidprocessObject(Elementbean,Listproperties)throwsClassNotFoundException,T11egalAccessException,InstantiationException,NoSuchFic1dExccption{Classclazz=Class.forName(bean,attributeValue(CommonConstant.CLASS));Objecttargetobject二clazz•newlnstance();for(Elementproperty:properties){StringficldNamc二property•attributcVeiluc(CommonConstant.NAME);Fieldfield=clazz・getDeclaredField(fieldMame);field.setAccessible(true);//含有value属性if(property,attributeValue(CommonConstant.VALUE)!=null){SimplcValucSctUtils.sctSimplcValuc(field,targctObjcct,property.attributeValue(CommonConstant.VALUE));}elseif(property.attributeValue(CommonConstant.REF)!=null){Stringrefid二property.attributeValue(CommonConstant.REF);Objectobject二POOL.getObject(refTd);field.sct(targctObjcct,object);}else{thrownewRuntimeException("neithervaluenorref〃);}}POOL.putObjcct(boan.attributcValuc(CommonConstant.ID),targctObjcct);}}注:上面代码只是对象池项目的XML解析部分,完整项目可参考git@git.oschina.net:feiqing/commons-frame.gitXPathXPdth是一门在XML文档中杳找信息的语言,XPath可用来在XML文档中对元素和屈性进行遍丿力.表达式/描述从根节点开始获取(/beans:匹配根下的;?/beans/bean:匹配F面的)//从当前文档中搜索,而不用考虑它们的位置(//property:匹配当询文档中所有〈property/〉)*肚配任何元素节点(/*:匹配所有标签)匹配属性(例:?//@name:匹配所有name属性)[position]位置谓语匹配(例:?//property[1]:匹配第一个;//property[last()]:匹配最后一个〈property/〉) [@attr]属性谓语匹配(例:?//bean[@id]:匹配所有带id属性的标签;?//bean[@id=idf]:匹配所有id属性值为'idl'的标签)谓语:谓语用来查找某个特定的节点或者包含某个指定的值的节点.XPath的语法详细内容可以参考W3SchoolXPath教程.Dom4j对XPath的支持默认的情况下Dom4j并不支持XPath,需耍在pom下添加如下依赖:jaxenjaxenl.1.6Dom4jNodc接口提供了方法对XPath支持:方法ListselectNodes(StringxpathExpression)ListselectNodes(StringxpathExpression,StringcomparisonXPathExpression)ListselectNodes(StringxpathExpression,StringcomparisonXPathExpression,booleanremoveDuplicates)ObjectselectObject(StringxpathExpression)NodesclcctSingleNodc(StringxpathExprcssion)XPath实现查询•查询所有bean标签上的属性值/***©authorjifang*@since16/1/20±午9:28.*/publicclassXPathRead{privateDocumentdocument;@BcforcpublicvoidsetUp()throwsDocumentException{document=XmlUtils.getXmlDocument(,zconfig.xmrz);} @Test@SupprcssWarnings(〃unchecked")publicvoidclient(){Listbeans=document.selectNodes(,z//bean,z);for(Elementbean:beans){System,out.printin(,zid:"+bean.attributeValueCzid,z)+",class:"+bean.attributcValuc(^class^));}}}XPath实现更新•删除idVid2”的vbean/>@Testpublicvoidclient(){Nodebean二documenl.selectSingleNode("//bean[@id="id2〃]");bean.getParent()・remove(bean);}参考:Dom4j的使用Java处理XML的三种主流技术及介绍

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
大家都在看
近期热门
关闭