XML是一种可扩展标记语言
下面是一个完整的XML文件(也是下文介绍读写XML的样本):
- <?xmlversion="1.0"encoding="UTF-8"?>
- <poemauthor="WilliamCarlosWilliams"title="TheGreatFigure">
- line>Amongtherain</>
- >andligths>Isawthefigure5>ingold>onared>firetruck>moving>tense>unheeded>togongclangs>sirenhowls>andwheelsrumbling>throughthedarkcitypoem>
一、写XML
本文介绍两种方式:使用DOM开发包来写XML文件和用String对象的方式
将Poem类作为数据源,提供需要转换成XML的内容:
classPoem{
- privatestaticStringtitle="TheGreatFigure";
- staticStringauthor="WilliamCarlosWilliams";
- staticArrayList<String>lines=newArrayList<String>();
- static{
- lines.add("Amongtherain");
- lines.add("andligths");
- lines.add("Isawthefigure5");
- lines.add("ingold");
- lines.add("onared");
- lines.add("firetruck");
- lines.add("moving");
- lines.add("tense");
- lines.add("unheeded");
- lines.add("togongclangs");
- lines.add("sirenhowls");
- lines.add("andwheelsrumbling");
- lines.add("throughthedarkcity");
- }
- publicstaticStringgetTitle(){
- returntitle;
- }
- staticStringgetAuthor(){
- returnauthor;
- staticArrayList<String>getLines(){
- returnlines;
- }
1、用DOM写XML文件
流程:
(1)创建一个空的Document对象(最顶层的DOM对象,包含了创建XML所需要的其他一切)。
(2)创建元素和属性,把元素和属性加到Document对象中。
(3)把Document对象的内容转换成String对象。
(4)把String对象写到目标文件里去。
importjava.util.ArrayList;
- importjava.io.*;
- importjavax.xml.parsers.*;
- importjavax.xml.transform.*;
- importjavax.xml.transform.dom.DOMSource;
- importjavax.xml.transform.stream.StreamResult;
- importorg.w3c.dom.*;
-
- classXmlTest{
- staticvoidmain(String[]args){
- Documentdoc=createXMLContent1();
- createElements(doc);
- StringxmlContent=createXMLString(doc);
- writeXMLToFile1(xmlContent);
-
- staticDocumentcreateXMLContent1(){
- Documentdoc=null;
- try{
- //使应用程序能够从XML文档获取生成DOM对象树的解析器
- DocumentBuilderFactorydbfac=DocumentBuilderFactory.newInstance();
- DocumentBuilderdocBuilder=dbfac.newDocumentBuilder();
- doc=docBuilder.newDocument();
- //作为XML声明的一部分指定此文档是否是单独的的属性。未指定时,此属性为false。
- doc.setXmlStandalone(true);
- }catch(ParserConfigurationExceptionpce){
- System.out.println("Couldn'tcreateaDocumentBuilder");
- System.exit(1);
- returndoc;
- voidcreateElements(Documentdoc){
-
- Elementpoem=doc.createElement("poem");
- poem.setAttribute("title",Poem.getTitle());
- poem.setAttribute("author",Poem.getAuthor());
- //把根元素加到文档里去
- doc.appendChild(poem);
- //创建子元素
- for(StringlineIn:Poem.getLines()){
- Elementline=doc.createElement("line");
- TextlineText=doc.createTextNode(lineIn);
- line.appendChild(lineText);
- //把每个元素加到根元素里去
- poem.appendChild(line);
- staticStringcreateXMLString(Documentdoc){
- //将DOM转换成字符串
- Transformertransformer= StringWriterstringWriter=newStringWriter();
- try{
- TransformerFactorytransformerFactory=TransformerFactory.newInstance();
- transformer=transformerFactory.newTransformer();
- //是否应输出XML声明
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
- //是否以XML格式自动换行
- transformer.setOutputProperty(OutputKeys.INDENT,0); background-color:inherit">//创建字符串以包含XML
- stringWriter=newStringWriter();
- StreamResultresult=newStreamResult(stringWriter);
- DOMSourcesource=newDOMSource(doc);
- transformer.transform(source,result);
- catch(TransformerConfigurationExceptione){
- System.out.println("Couldn'tcreateaTransformer");
- }catch(TransformerExceptione){
- System.out.println("Couldn'ttransformeDOMtoaString");
- System.exit(1);
- returnstringWriter.toString();
- voidwriteXMLToFile1(StringxmlContent){
- StringfileName="E:testdomoutput.xml";
- FiledomOutput=newFile(fileName);
- FileOutputStreamdomOutputStream=newFileOutputStream(domOutput);
- domOutputStream.write(xmlContent.getBytes());
- domOutputStream.close();
- System.out.println(fileName+"wassuccessfullywritten");
- catch(FileNotFoundExceptione){
- System.out.println("Couldn'tfindafilecalled"+fileName);
- catch(IOExceptione){
- System.out.println("Couldn'twriteafilecalled"+fileName);
- }
2、用String写XML文件
这种方法就比较简单,就是直接用字符串把整个XML文件描述出来,然后保存文件。
二、读取XML文件
两种方式:用DOM读取XML文件和用SAX方式。一般DOM处理内容比较小的XML文件,而SAX可以处理任意大小的XML文件。
1、用DOM读取XML文件
writeFileContentsToConsole(fileName);
- /***********用DOM读取XML文件***********/
- voidwriteFileContentsToConsole(StringfileName){
- Documentdoc=createDocument(fileName);
- Elementroot=doc.getDocumentElement();
- StringBuildersb=newStringBuilder();
- sb.append("Therootelementisnamed:""+root.getNodeName()+""");
- sb.append("andhasthefollowingattributes:");
- NamedNodeMapattributes=root.getAttributes();
- for(inti=0;i<attributes.getLength();i++){
- NodethisAttribute=attributes.item(i);
- sb.append(thisAttribute.getNodeName());
- sb.append("(""+thisAttribute.getNodeValue()+"")");
- if(i<attributes.getLength()-1){
- sb.append(",");
- System.out.println(sb);
- NodeListnodes=doc.getElementsByTagName("line");
- 0;i<nodes.getLength();i++){
- Elementelement=(Element)nodes.item(i);
- System.out.println("Foundanelementnamed""
- +element.getTagName()+"""
- +"Withthefollowingcontent:""
- +element.getTextContent()+""");
- staticDocumentcreateDocument(StringfileName){
- FilexmlFile= doc=docBuilder.parse(xmlFile);
- doc.setXmlStandalone(true);
- catch(IOExceptione){
- e.printStackTrace();
- catch(SAXExceptione){
- catch(ParserConfigurationExceptione){
- }
- *Output:
- *Therootelementisnamed:"poem"andhasthefollowingattributes:author("WilliamCarlosWilliams"),title("TheGreatFigure")
- *Foundanelementnamed"line"Withthefollowingcontent:"Amongtherain"
- *Foundanelementnamed"line"Withthefollowingcontent:"andligths"
- *......
- *///:~
2、用SAX读取XML文件
SAX是使用ContentHandler接口来公开解析事件,而且SAX包提供了一个默认实现类DefaultHandler,它的默认行为就是什么都不做。下面就通过XMLToConsoleHandler类来覆盖其中的一些方法,来捕获XML文件的内容。
importorg.w3c.dom.CharacterData;
- importorg.xml.sax.SAXException;
- importorg.xml.sax.helpers.DefaultHandler;
- classXmlTest{
- voidmain(String[]args){
- StringfileName="E:testdomoutput.xml";
- getFileContents(fileName);
- voidgetFileContents(StringfileName){
- XMLToConsoleHandlerhandler=newXMLToConsoleHandler();
- SAXParserFactoryfactory=SAXParserFactory.newInstance();
- SAXParsersaxParser=factory.newSAXParser();
- saxParser.parse(fileName,handler);
- e.printStackTrace();
- catch(ParserConfigurationExceptione){
- catch(SAXExceptione){
- /***********用SAX读取XML文件***********/
- classXMLToConsoleHandlerextendsDefaultHandler{
- voidcharacters(char[]content,intstart,153); background-color:inherit; font-weight:bold">intlength)
- throwsSAXException{
- System.out.println("Foundcontent:"+newString(content,start,length));
- voidendElement(Stringarg0,StringlocalName,StringqName)throwsSAXException{
- System.out.println("Foundtheendofanelementnamed""+qName+""");
- voidstartElement(Stringuri,StringqName,
- Attributesattributes) StringBuildersb=newStringBuilder();
- sb.append("Foundthestartofanelementnamed""+qName+""");
- if(attributes!=null&&attributes.getLength()>0){
- sb.append("withattributesnamed");
- 0;i<attributes.getLength();i++){
- StringattributeName=attributes.getLocalName(i);
- StringattributeValue=attributes.getValue(i);
- sb.append("""+attributeName+""");
- sb.append("(value=");
- sb.append("""+attributeValue+""");
- sb.append(")");
- System.out.println(sb.toString());
- }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|