|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
微软什么都提供了。你可以试想一下,如果你是新手,你是希望你点一下按钮程序就能运行那,还是想自己一点一点的组织结构,然后打包发部,调错再打包......xml|程序|教程sonnet.xml这是在本教程中贯串利用的示例XML文档。<?xmlversion="1.0"?><!DOCTYPEsonnetSYSTEM"sonnet.dtd"><sonnettype="Shakespearean"><author><last-name>Shakespeare</last-name><first-name>William</first-name><nationality>British</nationality><year-of-birth>1564</year-of-birth><year-of-death>1616</year-of-death></author><title>Sonnet130</title><text><line>Mymistress`eyesarenothinglikethesun,</line><line>Coralisfarmoreredthanherlipsred.</line><line>Ifsnowbewhite,whythenherbreastsaredun,</line><line>Ifhairsbewires,blackwiresgrowonherhead.</line><line>Ihaveseenrosesdamasked,redandwhite,</line><line>ButnosuchrosesseeIinhercheeks.</line><line>Andinsomeperfumesistheremoredelight</line><line>Thaninthebreaththatfrommymistressreeks.</line><line>Ilovetohearherspeak,yetwellIknow</line><line>Thatmusichathafarmorepleasingsound.</line><line>IgrantIneversawagoddessgo,</line><line>Mymistresswhenshewalks,treadsontheground.</line><line>Andyet,byHeaven,Ithinkmyloveasrare</line><line>Asanyshebeliedwithfalsecompare.</line></text></sonnet>sonnet.dtd这是我们示例文档所用的DTD。<!--sonnet.dtd--><!ELEMENTsonnet(author,title?,text)><!ATTLISTsonnettype(Shakespearean|Petrarchan)"Shakespearean"><!ELEMENTtext(line,line,line,line,line,line,line,line,line,line,line,line,line,line)><!ELEMENTauthor(last-name,first-name,nationality,year-of-birth?,year-of-death?)><!ELEMENTtitle(<!ELEMENTlast-name(<!ELEMENTfirst-name(<!ELEMENTnationality(<!ELEMENTyear-of-birth(<!ELEMENTyear-of-death(<!ELEMENTline(domOne.java这是我们的第一个DOM使用。它剖析一个XML文档并将其内容输入到尺度输入。/**(C)CopyrightIBMCorp.1999Allrightsreserved.**USGovernmentUsersRestrictedRightsUse,duplicationor*disclosurerestrictedbyGSAADPScheduleContractwithIBMCorp.**Theprogramisprovided"asis"withoutanywarrantyexpressor*implied,includingthewarrantyofnon-infringementandtheimplied*warrantiesofmerchantibilityandfitnessforaparticularpurpose.*IBMwillnotbeliableforanydamagessufferedbyyouasaresult*ofusingtheProgram.InnoeventwillIBMbeliableforany*special,indirectorconsequentialdamagesorlostprofitsevenif*IBMhasbeenadvisedofthepossibilityoftheiroccurrence.IBM*willnotbeliableforanythirdpartyclaimsagainstyou.*/importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.io.UnsupportedEncodingException;importorg.w3c.dom.Attr;importorg.w3c.dom.Document;importorg.w3c.dom.NamedNodeMap;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importcom.ibm.xml.parsers.*;/***domOne.java*IllustrateshowtogothroughaDOMtree.*/publicclassdomOne{publicvoidparseAndPrint(Stringuri){Documentdoc=null;try{DOMParserparser=newDOMParser();parser.parse(uri);doc=parser.getDocument();}catch(Exceptione){System.err.println("Sorry,anerroroccurred:"+e);}//We`veparsedthedocumentnow,solet`sprintit.if(doc!=null)printDOMTree(doc);}/**Printsthespecifiednode,thenprintsallofitschildren.*/publicvoidprintDOMTree(Nodenode){inttype=node.getNodeType();switch(type){//printthedocumentelementcaseNode.DOCUMENT_NODE:{System.out.println("<?xmlversion="1.0"?>");printDOMTree(((Document)node).getDocumentElement());break;}//printelementwithattributescaseNode.ELEMENT_NODE:{System.out.print("<");System.out.print(node.getNodeName());NamedNodeMapattrs=node.getAttributes();for(inti=0;i<attrs.getLength();i++){Nodeattr=attrs.item(i);System.out.print(""+attr.getNodeName()+"=""+attr.getNodeValue()+""");}System.out.println(">");NodeListchildren=node.getChildNodes();if(children!=null){intlen=children.getLength();for(inti=0;i<len;i++)printDOMTree(children.item(i));}break;}//handleentityreferencenodescaseNode.ENTITY_REFERENCE_NODE:{System.out.print("&");System.out.print(node.getNodeName());System.out.print(";");break;}//printcdatasectionscaseNode.CDATA_SECTION_NODE:{System.out.print("<![CDATA[");System.out.print(node.getNodeValue());System.out.print("]]>");break;}//printtextcaseNode.TEXT_NODE:{System.out.print(node.getNodeValue());break;}//printprocessinginstructioncaseNode.PROCESSING_INSTRUCTION_NODE:{System.out.print("<?");System.out.print(node.getNodeName());Stringdata=node.getNodeValue();{System.out.print("");System.out.print(data);}System.out.print("?>");break;}}if(type==Node.ELEMENT_NODE){System.out.println();System.out.print("</");System.out.print(node.getNodeName());System.out.print(`>`);}}/**Mainprogramentrypoint.*/publicstaticvoidmain(Stringargv[]){if(argv.length==0){System.out.println("Usage:javadomOneuri");System.out.println("whereuriistheURIoftheXMLdocumentyouwanttoprint.");System.out.println("Sample:javadomOnesonnet.xml");System.exit(1);}domOned1=newdomOne();d1.parseAndPrint(argv[0]);}}domCounter.java这段代码剖析一个XML文档,然后遍历DOM树来收罗有关该文档的数据。当数据收罗后将其输入到尺度输入。/**(C)CopyrightIBMCorp.1999Allrightsreserved.**USGovernmentUsersRestrictedRightsUse,duplicationor*disclosurerestrictedbyGSAADPScheduleContractwithIBMCorp.**Theprogramisprovided"asis"withoutanywarrantyexpressor*implied,includingthewarrantyofnon-infringementandtheimplied*warrantiesofmerchantibilityandfitnessforaparticularpurpose.*IBMwillnotbeliableforanydamagessufferedbyyouasaresult*ofusingtheProgram.InnoeventwillIBMbeliableforany*special,indirectorconsequentialdamagesorlostprofitsevenif*IBMhasbeenadvisedofthepossibilityoftheiroccurrence.IBM*willnotbeliableforanythirdpartyclaimsagainstyou.*/importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.io.UnsupportedEncodingException;importorg.w3c.dom.Document;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importcom.ibm.xml.parsers.DOMParser;/***domCounter.java*ThiscodecreatesaDOMparser,parsesadocument,then*printsstatisticsaboutthenumberandtypeofnodes*foundinthedocument.*/publicclassdomCounter{intdocumentNodes=0;intelementNodes=0;intentityReferenceNodes=0;intcdataSections=0;inttextNodes=0;intprocessingInstructions=0;publicvoidparseAndCount(Stringuri){Documentdoc=null;try{DOMParserparser=newDOMParser();parser.parse(uri);doc=parser.getDocument();}catch(Exceptione){System.err.println("Sorry,anerroroccurred:"+e);}//We`veparsedthedocumentnow,solet`sscantheDOMtreeand//printthestatistics.if(doc!=null){scanDOMTree(doc);System.out.println("DocumentStatisticsfor"+uri+":");System.out.println("====================================");System.out.println("DocumentNodes:"+documentNodes);System.out.println("ElementNodes:"+elementNodes);System.out.println("EntityReferenceNodes:"+entityReferenceNodes);System.out.println("CDATASections:"+cdataSections);System.out.println("TextNodes:"+textNodes);System.out.println("ProcessingInstructions:"+processingInstructions);System.out.println("----------");inttotalNodes=documentNodes+elementNodes+entityReferenceNodes+cdataSections+textNodes+processingInstructions;System.out.println("Total:"+totalNodes+"Nodes");}}/**ScanstheDOMtreeandcountsthedifferenttypesofnodes.*/publicvoidscanDOMTree(Nodenode){inttype=node.getNodeType();switch(type){caseNode.DOCUMENT_NODE:documentNodes++;scanDOMTree(((Document)node).getDocumentElement());break;caseNode.ELEMENT_NODE:elementNodes++;NodeListchildren=node.getChildNodes();if(children!=null){intlen=children.getLength();for(inti=0;i<len;i++)scanDOMTree(children.item(i));}break;caseNode.ENTITY_REFERENCE_NODE:entityReferenceNodes++;break;caseNode.CDATA_SECTION_NODE:cdataSections++;break;caseNode.TEXT_NODE:textNodes++;break;caseNode.PROCESSING_INSTRUCTION_NODE:processingInstructions++;break;}}/**Mainprogramentrypoint.*/publicstaticvoidmain(Stringargv[]){if(argv.length==0){System.out.println("Usage:javadomCounteruri");System.out.println("whereuriistheURIofyourXMLdocument.");System.out.println("Sample:javadomCountersonnet.xml");System.exit(1);}domCounterdc=newdomCounter();dc.parseAndCount(argv[0]);}}saxOne.java/**(C)CopyrightIBMCorp.1999Allrightsreserved.**USGovernmentUsersRestrictedRightsUse,duplicationor*disclosurerestrictedbyGSAADPScheduleContractwithIBMCorp.**Theprogramisprovided"asis"withoutanywarrantyexpressor*implied,includingthewarrantyofnon-infringementandtheimplied*warrantiesofmerchantibilityandfitnessforaparticularpurpose.*IBMwillnotbeliableforanydamagessufferedbyyouasaresult*ofusingtheProgram.InnoeventwillIBMbeliableforany*special,indirectorconsequentialdamagesorlostprofitsevenif*IBMhasbeenadvisedofthepossibilityoftheiroccurrence.IBM*willnotbeliableforanythirdpartyclaimsagainstyou.*/importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.io.UnsupportedEncodingException;importorg.xml.sax.AttributeList;importorg.xml.sax.HandlerBase;importorg.xml.sax.Parser;importorg.xml.sax.SAXException;importorg.xml.sax.SAXParseException;importorg.xml.sax.helpers.ParserFactory;importcom.ibm.xml.parsers.SAXParser;/***saxOne.java*ThissampleprogramillustrateshowtouseaSAXparser.It*parsesadocumentandwritesthedocument?contentsbackto*standardoutput.*/publicclasssaxOneextendsHandlerBase{publicvoidparseURI(Stringuri){SAXParserparser=newSAXParser();parser.setDocumentHandler(this);parser.setErrorHandler(this);try{parser.parse(uri);}catch(Exceptione){System.err.println(e);}}/**Processinginstruction.*/publicvoidprocessingInstruction(Stringtarget,Stringdata){System.out.print("<?");System.out.print(target);if(data!=null&&data.length()>0){System.out.print(``);System.out.print(data);}System.out.print("?>");}/**Startdocument.*/publicvoidstartDocument(){System.out.println("<?xmlversion="1.0"?>");}/**Startelement.*/publicvoidstartElement(Stringname,AttributeListattrs){System.out.print("<");System.out.print(name);if(attrs!=null){intlen=attrs.getLength();for(inti=0;i<len;i++){System.out.print("");System.out.print(attrs.getName(i));System.out.print("="");System.out.print(attrs.getValue(i));System.out.print(""");}}System.out.print(">");}/**Characters.*/publicvoidcharacters(charch[],intstart,intlength){System.out.print(newString(ch,start,length));}/**Ignorablewhitespace.*/publicvoidignorableWhitespace(charch[],intstart,intlength){characters(ch,start,length);}/**Endelement.*/publicvoidendElement(Stringname){System.out.print("</");System.out.print(name);System.out.print(">");}/**Enddocument.*/publicvoidendDocument(){//Noneedtodoanything.}////ErrorHandlermethods///**Warning.*/publicvoidwarning(SAXParseExceptionex){System.err.println("[Warning]"+getLocationString(ex)+":"+ex.getMessage());}/**Error.*/publicvoiderror(SAXParseExceptionex){System.err.println("[Error]"+getLocationString(ex)+":"+ex.getMessage());}/**Fatalerror.*/publicvoidfatalError(SAXParseExceptionex)throwsSAXException{System.err.println("[FatalError]"+getLocationString(ex)+":"+ex.getMessage());throwex;}/**Returnsastringofthelocation.*/privateStringgetLocationString(SAXParseExceptionex){StringBufferstr=newStringBuffer();StringsystemId=ex.getSystemId();if(systemId!=null){intindex=systemId.lastIndexOf(`/`);if(index!=-1)systemId=systemId.substring(index+1);str.append(systemId);}str.append(`:`);str.append(ex.getLineNumber());str.append(`:`);str.append(ex.getColumnNumber());returnstr.toString();}/**Mainprogramentrypoint.*/publicstaticvoidmain(Stringargv[]){if(argv.length==0){System.out.println("Usage:javasaxOneuri");System.out.println("whereuriistheURIofyourXMLdocument.");System.out.println("Sample:javasaxOnesonnet.xml");System.exit(1);}saxOnes1=newsaxOne();s1.parseURI(argv[0]);}}saxCounter.java/**(C)CopyrightIBMCorp.1999Allrightsreserved.**USGovernmentUsersRestrictedRightsUse,duplicationor*disclosurerestrictedbyGSAADPScheduleContractwithIBMCorp.**Theprogramisprovided"asis"withoutanywarrantyexpressor*implied,includingthewarrantyofnon-infringementandtheimplied*warrantiesofmerchantibilityandfitnessforaparticularpurpose.*IBMwillnotbeliableforanydamagessufferedbyyouasaresult*ofusingtheProgram.InnoeventwillIBMbeliableforany*special,indirectorconsequentialdamagesorlostprofitsevenif*IBMhasbeenadvisedofthepossibilityoftheiroccurrence.IBM*willnotbeliableforanythirdpartyclaimsagainstyou.*/importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.io.UnsupportedEncodingException;importorg.xml.sax.AttributeList;importorg.xml.sax.HandlerBase;importorg.xml.sax.Parser;importorg.xml.sax.SAXException;importorg.xml.sax.SAXParseException;importorg.xml.sax.helpers.ParserFactory;importcom.ibm.xml.parsers.SAXParser;/***saxCounter.java*ThissampleprogramcalculatesstatisticsforanXMLdocument,*basedontheSAXeventsreceived.Whentheparseiscomplete,*itprintsthestatisticstostandardoutput.*/publicclasssaxCounterextendsHandlerBase{intstartDocumentEvents=0;intendDocumentEvents=0;intstartElementEvents=0;intendElementEvents=0;intprocessingInstructionEvents=0;intcharacterEvents=0;intignorableWhitespaceEvents=0;intwarningEvents=0;interrorEvents=0;intfatalErrorEvents=0;publicvoidparseURI(Stringuri){SAXParserparser=newSAXParser();parser.setDocumentHandler(this);parser.setErrorHandler(this);try{parser.parse(uri);}catch(Exceptione){System.err.println(e);}System.out.println("DocumentStatisticsfor"+uri+":");System.out.println("====================================");System.out.println("DocumentHandlerEvents:");System.out.println("startDocument"+startDocumentEvents);System.out.println("endDocument"+endDocumentEvents);System.out.println("startElement"+startElementEvents);System.out.println("endElement"+endElementEvents);System.out.println("processingInstruction"+processingInstructionEvents);System.out.println("character"+characterEvents);System.out.println("ignorableWhitespace"+ignorableWhitespaceEvents);System.out.println("ErrorHandlerEvents:");System.out.println("warning"+warningEvents);System.out.println("error"+errorEvents);System.out.println("fatalError"+fatalErrorEvents);System.out.println("----------");inttotalEvents=startDocumentEvents+endDocumentEvents+startElementEvents+endElementEvents+processingInstructionEvents+characterEvents+ignorableWhitespaceEvents+warningEvents+errorEvents+fatalErrorEvents;System.out.println("Total:"+totalEvents+"Events");}/**Processinginstruction.*/publicvoidprocessingInstruction(Stringtarget,Stringdata){processingInstructionEvents++;}/**Startdocument.*/publicvoidstartDocument(){startDocumentEvents++;}/**Startelement.*/publicvoidstartElement(Stringname,AttributeListattrs){startElementEvents++;}/**Characters.*/publicvoidcharacters(charch[],intstart,intlength){characterEvents++;}/**Ignorablewhitespace.*/publicvoidignorableWhitespace(charch[],intstart,intlength){ignorableWhitespaceEvents++;}/**Endelement.*/publicvoidendElement(Stringname){endElementEvents++;}/**Enddocument.*/publicvoidendDocument(){endDocumentEvents++;}////ErrorHandlermethods///**Warning.*/publicvoidwarning(SAXParseExceptionex){warningEvents++;}/**Error.*/publicvoiderror(SAXParseExceptionex){errorEvents++;}/**Fatalerror.*/publicvoidfatalError(SAXParseExceptionex)throwsSAXException{fatalErrorEvents++;throwex;}/**Mainprogramentrypoint.*/publicstaticvoidmain(Stringargv[]){if(argv.length==0){System.out.println("Usage:javasaxCounteruri");System.out.println("whereuriistheURIofyourXMLdocument.");System.out.println("Sample:javasaxCountersonnet.xml");System.exit(1);}saxCountersc=newsaxCounter();sc.parseURI(argv[0]);}}
但是对于JAVA技术类的学习,我觉得大课堂反而会影响自身独立思考的过程,因为上课的时候,老师讲课的速度很快为了不遗漏要点,通常会仔细的听, |
|