加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

读写XML

发布时间:2020-12-16 05:52:30 所属栏目:百科 来源:网络整理
导读:XML是一种可扩展标记语言 下面是一个完整的XML文件(也是下文介绍读写XML的样本): [html] view plain copy ? xml version = "1.0" encoding = "UTF-8" ? poem author = "WilliamCarlosWilliams" title = "TheGreatFigure" line Amongtherain / andligths I

XML是一种可扩展标记语言

下面是一个完整的XML文件(也是下文介绍读写XML的样本):

[html] view plain copy
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <poemauthor="WilliamCarlosWilliams"title="TheGreatFigure">
  3. line>Amongtherain</>
  4. >andligths>Isawthefigure5>ingold>onared>firetruck>moving>tense>unheeded>togongclangs>sirenhowls>andwheelsrumbling>throughthedarkcitypoem>


一、写XML

本文介绍两种方式:使用DOM开发包来写XML文件和用String对象的方式

将Poem类作为数据源,提供需要转换成XML的内容:

[java] copy
    classPoem{
  1. privatestaticStringtitle="TheGreatFigure";
  2. staticStringauthor="WilliamCarlosWilliams";
  3. staticArrayList<String>lines=newArrayList<String>();
  4. static{
  5. lines.add("Amongtherain");
  6. lines.add("andligths");
  7. lines.add("Isawthefigure5");
  8. lines.add("ingold");
  9. lines.add("onared");
  10. lines.add("firetruck");
  11. lines.add("moving");
  12. lines.add("tense");
  13. lines.add("unheeded");
  14. lines.add("togongclangs");
  15. lines.add("sirenhowls");
  16. lines.add("andwheelsrumbling");
  17. lines.add("throughthedarkcity");
  18. }
  19. publicstaticStringgetTitle(){
  20. returntitle;
  21. }
  22. staticStringgetAuthor(){
  23. returnauthor;
  24. staticArrayList<String>getLines(){
  25. returnlines;
  26. }


1、用DOM写XML文件

流程:

(1)创建一个空的Document对象(最顶层的DOM对象,包含了创建XML所需要的其他一切)。

(2)创建元素和属性,把元素和属性加到Document对象中。

(3)把Document对象的内容转换成String对象。

(4)把String对象写到目标文件里去。

copy
    importjava.util.ArrayList;
  1. importjava.io.*;
  2. importjavax.xml.parsers.*;
  3. importjavax.xml.transform.*;
  4. importjavax.xml.transform.dom.DOMSource;
  5. importjavax.xml.transform.stream.StreamResult;
  6. importorg.w3c.dom.*;
  7. classXmlTest{
  8. staticvoidmain(String[]args){
  9. Documentdoc=createXMLContent1();//创建空文档
  10. createElements(doc);//创建XML
  11. StringxmlContent=createXMLString(doc);//创建字符串以表示XML
  12. writeXMLToFile1(xmlContent);
  13. /***********用DOM写XML文件***********/
  14. staticDocumentcreateXMLContent1(){
  15. Documentdoc=null;
  16. try{
  17. //使应用程序能够从XML文档获取生成DOM对象树的解析器
  18. DocumentBuilderFactorydbfac=DocumentBuilderFactory.newInstance();
  19. DocumentBuilderdocBuilder=dbfac.newDocumentBuilder();
  20. doc=docBuilder.newDocument();
  21. //作为XML声明的一部分指定此文档是否是单独的的属性。未指定时,此属性为false。
  22. doc.setXmlStandalone(true);
  23. }catch(ParserConfigurationExceptionpce){
  24. System.out.println("Couldn'tcreateaDocumentBuilder");
  25. System.exit(1);
  26. returndoc;
  27. voidcreateElements(Documentdoc){
  28. //创建根元素
  29. Elementpoem=doc.createElement("poem");
  30. poem.setAttribute("title",Poem.getTitle());
  31. poem.setAttribute("author",Poem.getAuthor());
  32. //把根元素加到文档里去
  33. doc.appendChild(poem);
  34. //创建子元素
  35. for(StringlineIn:Poem.getLines()){
  36. Elementline=doc.createElement("line");
  37. TextlineText=doc.createTextNode(lineIn);
  38. line.appendChild(lineText);
  39. //把每个元素加到根元素里去
  40. poem.appendChild(line);
  41. staticStringcreateXMLString(Documentdoc){
  42. //将DOM转换成字符串
  43. Transformertransformer= StringWriterstringWriter=newStringWriter();
  44. try{
  45. TransformerFactorytransformerFactory=TransformerFactory.newInstance();
  46. transformer=transformerFactory.newTransformer();
  47. //是否应输出XML声明
  48. transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  49. //是否以XML格式自动换行
  50. transformer.setOutputProperty(OutputKeys.INDENT,0); background-color:inherit">//创建字符串以包含XML
  51. stringWriter=newStringWriter();
  52. StreamResultresult=newStreamResult(stringWriter);//充当转换结果的持有者
  53. DOMSourcesource=newDOMSource(doc);
  54. transformer.transform(source,result);
  55. catch(TransformerConfigurationExceptione){
  56. System.out.println("Couldn'tcreateaTransformer");
  57. }catch(TransformerExceptione){
  58. System.out.println("Couldn'ttransformeDOMtoaString");
  59. System.exit(1);
  60. returnstringWriter.toString();
  61. voidwriteXMLToFile1(StringxmlContent){
  62. StringfileName="E:testdomoutput.xml";
  63. FiledomOutput=newFile(fileName);
  64. FileOutputStreamdomOutputStream=newFileOutputStream(domOutput);
  65. domOutputStream.write(xmlContent.getBytes());
  66. domOutputStream.close();
  67. System.out.println(fileName+"wassuccessfullywritten");
  68. catch(FileNotFoundExceptione){
  69. System.out.println("Couldn'tfindafilecalled"+fileName);
  70. catch(IOExceptione){
  71. System.out.println("Couldn'twriteafilecalled"+fileName);
  72. }


2、用String写XML文件

这种方法就比较简单,就是直接用字符串把整个XML文件描述出来,然后保存文件。


二、读取XML文件

两种方式:用DOM读取XML文件和用SAX方式。一般DOM处理内容比较小的XML文件,而SAX可以处理任意大小的XML文件。


1、用DOM读取XML文件

copy
    writeFileContentsToConsole(fileName);
  1. /***********用DOM读取XML文件***********/
  2. voidwriteFileContentsToConsole(StringfileName){
  3. Documentdoc=createDocument(fileName);
  4. Elementroot=doc.getDocumentElement();//获取根元素
  5. StringBuildersb=newStringBuilder();
  6. sb.append("Therootelementisnamed:""+root.getNodeName()+""");
  7. sb.append("andhasthefollowingattributes:");
  8. NamedNodeMapattributes=root.getAttributes();
  9. for(inti=0;i<attributes.getLength();i++){
  10. NodethisAttribute=attributes.item(i);
  11. sb.append(thisAttribute.getNodeName());
  12. sb.append("(""+thisAttribute.getNodeValue()+"")");
  13. if(i<attributes.getLength()-1){
  14. sb.append(",");
  15. System.out.println(sb);//根元素的描述信息
  16. NodeListnodes=doc.getElementsByTagName("line");
  17. 0;i<nodes.getLength();i++){
  18. Elementelement=(Element)nodes.item(i);
  19. System.out.println("Foundanelementnamed""
  20. +element.getTagName()+"""
  21. +"Withthefollowingcontent:""
  22. +element.getTextContent()+""");
  23. staticDocumentcreateDocument(StringfileName){//从文件创建DOM的Document对象
  24. FilexmlFile= doc=docBuilder.parse(xmlFile);//解析xml文件加载为dom文档
  25. doc.setXmlStandalone(true);
  26. catch(IOExceptione){
  27. e.printStackTrace();
  28. catch(SAXExceptione){
  29. catch(ParserConfigurationExceptione){
  30. }/*
  31. *Output:
  32. *Therootelementisnamed:"poem"andhasthefollowingattributes:author("WilliamCarlosWilliams"),title("TheGreatFigure")
  33. *Foundanelementnamed"line"Withthefollowingcontent:"Amongtherain"
  34. *Foundanelementnamed"line"Withthefollowingcontent:"andligths"
  35. *......
  36. *///:~


2、用SAX读取XML文件

SAX是使用ContentHandler接口来公开解析事件,而且SAX包提供了一个默认实现类DefaultHandler,它的默认行为就是什么都不做。下面就通过XMLToConsoleHandler类来覆盖其中的一些方法,来捕获XML文件的内容。

copy
    importorg.w3c.dom.CharacterData;
  1. importorg.xml.sax.SAXException;
  2. importorg.xml.sax.helpers.DefaultHandler;
  3. classXmlTest{
  4. voidmain(String[]args){
  5. StringfileName="E:testdomoutput.xml";
  6. getFileContents(fileName);
  7. voidgetFileContents(StringfileName){
  8. XMLToConsoleHandlerhandler=newXMLToConsoleHandler();
  9. SAXParserFactoryfactory=SAXParserFactory.newInstance();
  10. SAXParsersaxParser=factory.newSAXParser();
  11. saxParser.parse(fileName,handler);
  12. e.printStackTrace();
  13. catch(ParserConfigurationExceptione){
  14. catch(SAXExceptione){
  15. /***********用SAX读取XML文件***********/
  16. classXMLToConsoleHandlerextendsDefaultHandler{
  17. voidcharacters(char[]content,intstart,153); background-color:inherit; font-weight:bold">intlength)
  18. throwsSAXException{//处理元素的真正内容
  19. System.out.println("Foundcontent:"+newString(content,start,length));
  20. voidendElement(Stringarg0,StringlocalName,StringqName)throwsSAXException{
  21. System.out.println("Foundtheendofanelementnamed""+qName+""");
  22. voidstartElement(Stringuri,StringqName,
  23. Attributesattributes) StringBuildersb=newStringBuilder();
  24. sb.append("Foundthestartofanelementnamed""+qName+""");
  25. if(attributes!=null&&attributes.getLength()>0){
  26. sb.append("withattributesnamed");
  27. 0;i<attributes.getLength();i++){
  28. StringattributeName=attributes.getLocalName(i);
  29. StringattributeValue=attributes.getValue(i);
  30. sb.append("""+attributeName+""");
  31. sb.append("(value=");
  32. sb.append("""+attributeValue+""");
  33. sb.append(")");
  34. System.out.println(sb.toString());
  35. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读