packagesample; importjava.io.BufferedReader; importjava.io.File; importjava.io.FileReader; importjava.io.IOException; importjava.io.OutputStream; importjava.io.StringReader; importjava.io.Writer; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importjavax.xml.parsers.ParserConfigurationException; importjavax.xml.transform.OutputKeys; importjavax.xml.transform.Transformer; importjavax.xml.transform.TransformerException; importjavax.xml.transform.TransformerFactory; importjavax.xml.transform.dom.Domresult; importjavax.xml.transform.dom.DOMSource; importjavax.xml.transform.stream.StreamResult; importjavax.xml.transform.stream.StreamSource; importorg.w3c.dom.DOMException; importorg.w3c.dom.Document; importorg.w3c.dom.Element; importorg.w3c.dom.Node; importorg.w3c.dom.NodeList; importorg.xml.sax.InputSource; importorg.xml.sax.SAXException; /** *XMLutilityclass. * *@author$Author:LihongGao$ */ publicfinalclassXMLUtil{ /**Hidedefaultconstructor*/ privateXMLUtil(){ } /** *SelectssinglenodespecifiedbytheXPathexpression. * *@paramcurrent *XPathqueryrootnode *@paramxpath *XPathexpression *@returnSelectednode *@throwsAIUException *Indicatesmorethanonenodesareselected */ publicstaticNodeselectSingleNode(Nodecurrent,Stringxpath) throwsException{ //finalStringmethod="selectSingleNode(Node,String)"; NodeListlist=selectNodes(current,xpath); if(list==null||list.getLength()==0){ returnnull; }elseif(list.getLength()==1){ returnlist.item(0); }else{ thrownewException("Morethanonenodesareselected"); } } /** *SelectslistofnodesspecifiedbytheXPathexpression. * *@paramcurrent *XPathqueryrootnode *@paramxpath *XPathexpression *@returnSelectednodelist *@throwsAIUException *IndicatesXMLtransformfailure */ publicstaticNodeListselectNodes(Nodecurrent,Stringxpath) throwsException{ //finalStringmethod="selectNodes(Node,String)"; if(currentinstanceofElement&&xpath.indexOf('/')==-1 &&xpath.indexOf('[')==-1){ return((Element)current).getElementsByTagName(xpath); }else{ StringxltString="<?xmlversion=\"1.0\"encoding=\"utf-8\"?>" +"<xsl:stylesheetversion=\"1.0\"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +"<xsl:outputversion=\"1.0\"method=\"xml\"encoding=\"utf-8\"/>" +"<xsl:templatematch=\""+xpath+"\">" +"<xsl:copy-ofselect=\".\"/>"+"</xsl:template>" +"<xsl:templatematch=\"text()\"/>"+"</xsl:stylesheet>"; try{ Elementresult=(Element)current.cloneNode(false); StreamSourcetemplate=newStreamSource(newStringReader( xltString)); TransformerFactorytransformerFactory=TransformerFactory .newInstance(); Transformertransformer=transformerFactory .newTransformer(template); transformer.transform(newDOMSource(current),newDomresult( result)); returnresult.getChildNodes(); }catch(TransformerExceptionex){ thrownewException(ex.getMessage(),ex); } } } /** *Retrievestextnodevaluesastextrecursively. * *@paramroot *Rootnode *@paramxpath *XPathexpression *@returnStringrepresentationoftextnodes *@throwsException *Indicatesmorethanonenodesareselected */ publicstaticStringgetTextValue(Noderoot,Stringxpath)throwsException{ StringBufferbuf=newStringBuffer(); Nodenode=selectSingleNode(root,xpath); if(node==null){ returnnull; } NodeListchildren=node.getChildNodes(); for(inti=0;i<children.getLength();i++){ Nodechild=children.item(i); if(child.getNodeType()==Node.TEXT_NODE){ buf.append(child.getNodeValue()); } } returnbuf.toString(); } /** *Removesallelementsspecifiedbyelementname. * *@paramnode *Nodetomodify *@paramname *Elementname */ publicstaticvoidremoveNode(Nodenode,Stringname){ NodeListnodes=((Element)node).getElementsByTagName(name); if(nodes!=null){ for(inti=0;i<nodes.getLength();i++){ node.removeChild(nodes.item(i)); } } } /** *ExportsDOMnodetreetospecifiedoutputstream. * *@paramroot *Rootnode *@paramout *Outputwriter *@throwsException *IndicatesFailedtoexportnodes */ publicstaticvoidexportNodes(Noderoot,Writerout)throwsException{ exportNodes(root,newStreamResult(out)); } /** *ExportsDOMnodetreetospecifiedoutputstream. * *@paramroot *Rootnode *@paramout *Outputstream *@throwsException *IndicatesFailedtoexportnodes */ publicstaticvoidexportNodes(Noderoot,OutputStreamout) throwsException{ exportNodes(root,newStreamResult(out)); } /** *ExportsDOMnodetreetospecifiedoutputstream. * *@paramroot *Rootnode *@paramresult *Result *@throwsException *IndicatesFailedtoexportnodes */ publicstaticvoidexportNodes(Noderoot,StreamResultresult) throwsException{ //finalStringmethod="exportNodes(Node,OutputStream)"; finalStringxltString="<?xmlversion=\"1.0\"encoding=\"Shift_JIS\"?>" +"<xsl:stylesheetversion=\"1.0\"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +"<xsl:outputmethod=\"xml\"version=\"1.0\"encoding=\"Shift_JIS\"omit-xml-declaration=\"yes\"/>" +"<xsl:templatematch=\"*\">" +"<xsl:copy-ofselect=\".\"/>" +"</xsl:template>"+"</xsl:stylesheet>"; try{ StreamSourcetemplate=newStreamSource( newStringReader(xltString)); TransformerFactoryfactory=TransformerFactory.newInstance(); Transformertransformer=factory.newTransformer(template); transformer.setoutputProperty(OutputKeys.ENCODING,"Shift_JIS"); transformer.transform(newDOMSource(root),result); }catch(TransformerExceptionex){ thrownewTransformerException(ex.getMessage(),ex); } } /** *ConvertsNodetoDocument. * *@paramnode *Node *@returnDocument *@throwsException *IndicatesFailedtoconvert. */ publicstaticDocumentconvertTodocument(Nodenode)throwsException{ Documentdoc=createDocument(); doc.appendChild(doc.importNode(node,true)); returndoc; } /** *ConstructsnewDocument. * *@returnDocument *@throwsException *IndicatesFailedtoconvert. */ publicstaticDocumentcreateDocument()throwsException{ //finalStringmethod="createDocument()"; try{ DocumentBuilderFactoryfactory=DocumentBuilderFactory .newInstance(); DocumentBuilderbuilder=factory.newDocumentBuilder(); returnbuilder.newDocument(); }catch(DOMExceptione){ thrownewDOMException(ISeverityLevels.IMPORTANT,e.getMessage()); }catch(ParserConfigurationExceptione){ thrownewParserConfigurationException(e.getMessage()); } } /** *ParsesspecifiedXMLandreturnsconstructeddocument. * *@paramxml *XMLtoparse *@returnDocument *@throwsException *IndicatesFailedtoconvert. */ publicstaticDocumentparseDocument(Stringxml)throwsException{ //finalStringmethod="parseDocument(String)"; try{ DocumentBuilderFactoryfactory=DocumentBuilderFactory .newInstance(); DocumentBuilderbuilder=factory.newDocumentBuilder(); returnbuilder.parse(newInputSource(newStringReader(xml))); }catch(IOExceptione){ thrownewIOException(e.getMessage(),e); }catch(DOMExceptione){ thrownewDOMException(ISeverityLevels.IMPORTANT,e.getMessage()); }catch(ParserConfigurationExceptione){ thrownewParserConfigurationException(e.getMessage()); }catch(SAXExceptione){ thrownewSAXException(e.getMessage(),e); } } publicinterfaceISeverityLevels{ //severitylevelsforExceptionsandLogging publicfinalstaticshortCRITICAL=1; publicfinalstaticshortIMPORTANT=4; publicfinalstaticshortWARNING=7; publicfinalstaticshortinformatIONAL=10; publicfinalstaticshortDEBUG=13; publicfinalstaticshortVERBOSE=16; } publicstaticStringgetXmlString(StringinFilename)throwsException{ StringBuffersb=newStringBuffer(); BufferedReaderreader=newBufferedReader(newFileReader(newFile( inFilename))); try{ Stringline=null; while((line=reader.readLine())!=null){ sb.append(line); } returnsb.toString(); }finally{ reader.close(); } } }
原文地址:https://www.jb51.cc/xml/299345.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。