前端之家收集整理的这篇文章主要介绍了
XML Utility,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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.f2er.com/xml/299345.html