• <sub id="h4knl"><ol id="h4knl"></ol></sub>
    <sup id="h4knl"></sup>
      <sub id="h4knl"></sub>

      <sub id="h4knl"><ol id="h4knl"><em id="h4knl"></em></ol></sub><s id="h4knl"></s>
      1. <strong id="h4knl"></strong>

      2. 用Java如何處理XML數(shù)據(jù)

        時(shí)間:2024-10-22 07:43:52 JAVA認(rèn)證 我要投稿
        • 相關(guān)推薦

        用Java如何處理XML數(shù)據(jù)

          Java原生內(nèi)置的處理XML的技術(shù)基本有這么幾種:DOM,SAX,Stax,Jaxb.那么用Java我們要如何處理XML數(shù)據(jù),希望對(duì)大家有幫助!

          DOM :Document Object Model 顧名思義就是在內(nèi)存中構(gòu)建樹(shù)形結(jié)構(gòu)。處理小的XML文件還算勉強(qiáng)應(yīng)付。如果文件比較大,他需要一次性裝載整個(gè)XML,你會(huì)忍不了他的速度,并且他會(huì)吃光你所有的內(nèi)存,最后程序會(huì)負(fù)分滾粗。

          SAX:Simple API for XML Parsing 一般名字應(yīng)該是沒(méi)實(shí)現(xiàn)的愿望體現(xiàn)。比如一個(gè)人如果叫王金庫(kù),那么可以肯定他絕對(duì)沒(méi)有金庫(kù)。這樣你應(yīng)該理解這個(gè)API為啥叫Simple了。這API是回調(diào)式的,也就是你寫(xiě)的程序是被別人調(diào)戲用的。這API比DOM快點(diǎn),而且是可以部分裝載XML,這樣你不用害怕OOME了。啥?你想寫(xiě)XML?忘掉這個(gè)叫Simple的玩意兒吧。

          Stax: Streaming API for XML 這個(gè)總算是靠點(diǎn)譜了。你寫(xiě)的程序是主動(dòng)式的訪問(wèn)XML各個(gè)節(jié)點(diǎn)。流式訪問(wèn),不用擔(dān)心OOME,速度嘛算是原生態(tài)里面最好的了。而且讀寫(xiě)都支持,你不用這個(gè)還用哪個(gè)啊?

          給個(gè)Stax的代碼片段,算是參考吧:

          XMLInputFactory xif = XMLInputFactory.newInstance();

          XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));

          xsr.nextTag(); // Advance to statements element

          long i = 0;

          String action = null;

          while (xsr.hasNext()) {

          if (xsr.next() == XMLStreamConstants.START_ELEMENT) {

          if ("ContentItem".equals(xsr.getLocalName())) {

          action = getAttributeValue(xsr, "action");

          } else if ("Data".equals(xsr.getLocalName())) {

          i ++;

          }

          }

          }

          JAXB:Java Architecture for XML Binding 這是一個(gè)很酷的API.想法就是把XML各種屬性定義映射到普通的Java Bean上。你無(wú)須關(guān)心解析反解析的細(xì)節(jié),只要用普通的Java Bean就完成和XML的交互了。可是怎么構(gòu)建一一映射的JavaBean呢?在已知XML的定義的情況下你可以用自帶的xjc 命令自動(dòng)生成相對(duì)應(yīng)的JavaBean.如果你用Eclipse,有類(lèi)似的插件幫你完成這步。具體可以google一下。然后你要做的就是僅僅是使用數(shù)據(jù)啦。簡(jiǎn)單的令人發(fā)指:

          JAXBContext jc = JAXBContext.newInstance("com.your.xml.datatype.bean"); // 先注冊(cè)你的JavaBean

          // Create unmarshaller

          Unmarshaller um = jc.createUnmarshaller();

          // Unmarshal XML contents of the file myDoc.xml into your Java object

          // instance

          ObjectFactory objFac = new ObjectFactory(); // 生成Bean之后你會(huì)有這個(gè)工廠類(lèi)的

          objFac.createYourData(objFac.createYourDataType());

          BufferedInputStream bis = new BufferedInputStream(new FileInputStream("your.xml")); // 你要怎么打開(kāi)你的XML文件呢?

          JAXBElement myJAXBObject = (JAXBElement) um.unmarshal(bis); // 讀取

          YourDataType yourData = (YourDataType) myJAXBObject.getValue(); // 可以用啦

          // 下面是寫(xiě)XML的例子

          Marshaller m = jc.createMarshaller();

          m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

          File outfile = new File("yourOutput.xml");

          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outfile), 4096);

          m.marshal(myJAXBObject, bos); // 一步寫(xiě)入。 myJAXBObject 需要你自己構(gòu)建,你要存什么呢

          try {

          bos.flush();

          } catch (IOException e) {

          // TODO Auto-generated catch block

          e.printStackTrace();

          } finally {

          try {

          bos.close();

          } catch (Exception e) {

          // TODO Auto-generated catch block

          e.printStackTrace();

          }

          }

          你也許意識(shí)到問(wèn)題了:這一下子把XML Load到內(nèi)存里,你是不是瘋了?為了避免瘋掉,你可以用Satx啊,那玩意兒不是流式的么?給個(gè)栗子,讀取這樣的XML文件片段:

          <OutXMLData>
          <SubXMLItemType>
          …
          </SubXMLItemType>
          <SubXMLItemType>
          …
          </SubXMLItemType>
          <SubXMLItemType>
          …
          </SubXMLItemType>
          …
          </OutXMLData>

          private static void readWriteWithStAXAndJAXB() throws FactoryConfigurationError, FileNotFoundException, XMLStreamException, UnsupportedEncodingException, JAXBException,

          PropertyException {

          // set up a StAX reader

          XMLInputFactory xmlif = XMLInputFactory.newInstance();

          BufferedInputStream bis = new BufferedInputStream(new FileInputStream("inputLarge.xml"));

          XMLStreamReader xmlr = xmlif.createXMLStreamReader(bis);

          File outfile = new File("output\outfile.xml");

          OutputStreamWriter bos = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8");

          XMLOutputFactory xmlof = XMLOutputFactory.newInstance();

          XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(bos);

          xmlw.writeStartDocument("UTF-8", "1.0");

          xmlw.writeStartElement("OutXMLData");

          JAXBContext ucontext = JAXBContext.newInstance(SubXMLItemType.class);

          Unmarshaller unmarshaller = ucontext.createUnmarshaller();

          Marshaller marshaller = ucontext.createMarshaller();

          marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

          marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

          xmlr.nextTag();

          xmlr.require(XMLStreamConstants.START_ELEMENT, null, "OutXMLData");

          xmlr.nextTag();

          int iCount = 0;

          while (xmlr.getEventType() == XMLStreamConstants.START_ELEMENT) { // 按標(biāo)簽流式讀取

          iCount++;

          JAXBElement pt = unmarshaller.unmarshal(xmlr, SubXMLItemType.class); // 只讀取映射SubItem的內(nèi)容

          marshaller.marshal(pt, xmlw); // 這步是分批流式寫(xiě)入

          xmlw.writeCharacters(" ");

          if (xmlr.getEventType() == XMLStreamConstants.CHARACTERS) {

          xmlr.next();

          }

          }

          xmlw.flush();

          xmlw.writeEndElement();

          xmlw.writeEndDocument();

          System.out.println("Entity Count is :" + iCount);

          xmlr.close();

          xmlw.close();

          }

          說(shuō)完這么多,基本上用Java處理XML已經(jīng)不是難事了。不過(guò),有時(shí)候你會(huì)有:給你蟹八件兒,你也無(wú)從下嘴的感受。比如,解析XML你可以掌控,隨便你用啥,可是你調(diào)用的下游程序接口卻需要另外一種格式的數(shù)據(jù)。比如,你用Stax解析XML,下游要DOM接口會(huì)不會(huì)令你抓狂起來(lái)?心里咒罵,倒霉玩意兒,你們還有沒(méi)有點(diǎn)上進(jìn)心?!最近我就遇到這事了,解析一個(gè)大的XML,下游要Sub的XML,或者叫XML片段,或者叫分割XML文件。好么,我把數(shù)據(jù)都拆成Java的Object,然后再給你拼成一個(gè)個(gè)小的XML文件發(fā)過(guò)去,喪心病狂么這不?!你如果真這么做了,就別往下看了,你會(huì)哭的!

          Java 的XML包下面有個(gè)transform的子包,看看里面會(huì)有驚喜的。可以用這個(gè)工具包幫你完成類(lèi)似的轉(zhuǎn)換,比如Stax 和 Sax 或者Dom 互相的變換。或者變換成Stream.

          拿我這個(gè)分割XML的小栗子來(lái)說(shuō):

          XMLInputFactory xif = XMLInputFactory.newInstance();

          XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml")); // 用Stax讀取XML

          xsr.nextTag(); // Advance to statements element

          TransformerFactory tf = TransformerFactory.newInstance();

          Transformer t = tf.newTransformer();

          t.setParameter(OutputKeys.OMIT_XML_DECLARATION, "no");

          t.setParameter(OutputKeys.STANDALONE, "yes");

          long i = 0;

          String action = null;

          while (xsr.hasNext()) {

          if (xsr.next() == XMLStreamConstants.START_ELEMENT) {

          if ("ContentItem".equals(xsr.getLocalName())) {

          action = getAttributeValue(xsr, "action");

          } else if ("Data".equals(xsr.getLocalName())) {

          File file = new File("out/" + action + i++ + ".xml");

          t.transform(new StAXSource(xsr), new StreamResult(file)); // 流式變換,走你~

          // DOMResult dr = new DOMResult(); // 如果你要Dom格式的,releaseMe

          // t.transform(new StAXSource(xsr), dr);

          }

          }

          }

          知道最變態(tài)的是什么嗎?需要解析XML整個(gè)內(nèi)容到String里面,不單單是數(shù)據(jù),就是整個(gè)XML標(biāo)簽和數(shù)據(jù)。其實(shí)就是ouputStream轉(zhuǎn)String的過(guò)程:

          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          t.transform(new StAXSource(xsr), new StreamResult(baos));

          String subXMLStr = baos.toString();

        《&.doc》
        将本文的Word文档下载到电脑,方便收藏和打印
        推荐度:
        点击下载文档

        【用Java如何處理XML數(shù)據(jù)】相關(guān)文章:

        關(guān)于XML技術(shù)在數(shù)據(jù)交換中的應(yīng)用03-29

        Java中日期的處理方法03-09

        如何編譯java程序03-05

        如何讓JAVA代碼更高效03-20

        java數(shù)據(jù)類(lèi)型和運(yùn)算符03-06

        Excel如何橫向輸入數(shù)據(jù)03-03

        Java如何實(shí)現(xiàn)簡(jiǎn)單的whois查詢03-16

        Java byte[]轉(zhuǎn)int如何實(shí)現(xiàn)03-16

        word表格中的數(shù)據(jù)如何排序02-21

        在线咨询
        国产高潮无套免费视频_久久九九兔免费精品6_99精品热6080YY久久_国产91久久久久久无码
      3. <sub id="h4knl"><ol id="h4knl"></ol></sub>
        <sup id="h4knl"></sup>
          <sub id="h4knl"></sub>

          <sub id="h4knl"><ol id="h4knl"><em id="h4knl"></em></ol></sub><s id="h4knl"></s>
          1. <strong id="h4knl"></strong>

          2. 亚洲成色999久久网站 | 亚洲国产一区二区三区在线观看 | 五月婷婷之综合缴情 | 亚洲男人的天堂色偷免费 | 鲁鲁天天在线视频 | 中出仑乱中文字幕在线 |

            用Java如何處理XML數(shù)據(jù)

              Java原生內(nèi)置的處理XML的技術(shù)基本有這么幾種:DOM,SAX,Stax,Jaxb.那么用Java我們要如何處理XML數(shù)據(jù),希望對(duì)大家有幫助!

              DOM :Document Object Model 顧名思義就是在內(nèi)存中構(gòu)建樹(shù)形結(jié)構(gòu)。處理小的XML文件還算勉強(qiáng)應(yīng)付。如果文件比較大,他需要一次性裝載整個(gè)XML,你會(huì)忍不了他的速度,并且他會(huì)吃光你所有的內(nèi)存,最后程序會(huì)負(fù)分滾粗。

              SAX:Simple API for XML Parsing 一般名字應(yīng)該是沒(méi)實(shí)現(xiàn)的愿望體現(xiàn)。比如一個(gè)人如果叫王金庫(kù),那么可以肯定他絕對(duì)沒(méi)有金庫(kù)。這樣你應(yīng)該理解這個(gè)API為啥叫Simple了。這API是回調(diào)式的,也就是你寫(xiě)的程序是被別人調(diào)戲用的。這API比DOM快點(diǎn),而且是可以部分裝載XML,這樣你不用害怕OOME了。啥?你想寫(xiě)XML?忘掉這個(gè)叫Simple的玩意兒吧。

              Stax: Streaming API for XML 這個(gè)總算是靠點(diǎn)譜了。你寫(xiě)的程序是主動(dòng)式的訪問(wèn)XML各個(gè)節(jié)點(diǎn)。流式訪問(wèn),不用擔(dān)心OOME,速度嘛算是原生態(tài)里面最好的了。而且讀寫(xiě)都支持,你不用這個(gè)還用哪個(gè)啊?

              給個(gè)Stax的代碼片段,算是參考吧:

              XMLInputFactory xif = XMLInputFactory.newInstance();

              XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));

              xsr.nextTag(); // Advance to statements element

              long i = 0;

              String action = null;

              while (xsr.hasNext()) {

              if (xsr.next() == XMLStreamConstants.START_ELEMENT) {

              if ("ContentItem".equals(xsr.getLocalName())) {

              action = getAttributeValue(xsr, "action");

              } else if ("Data".equals(xsr.getLocalName())) {

              i ++;

              }

              }

              }

              JAXB:Java Architecture for XML Binding 這是一個(gè)很酷的API.想法就是把XML各種屬性定義映射到普通的Java Bean上。你無(wú)須關(guān)心解析反解析的細(xì)節(jié),只要用普通的Java Bean就完成和XML的交互了。可是怎么構(gòu)建一一映射的JavaBean呢?在已知XML的定義的情況下你可以用自帶的xjc 命令自動(dòng)生成相對(duì)應(yīng)的JavaBean.如果你用Eclipse,有類(lèi)似的插件幫你完成這步。具體可以google一下。然后你要做的就是僅僅是使用數(shù)據(jù)啦。簡(jiǎn)單的令人發(fā)指:

              JAXBContext jc = JAXBContext.newInstance("com.your.xml.datatype.bean"); // 先注冊(cè)你的JavaBean

              // Create unmarshaller

              Unmarshaller um = jc.createUnmarshaller();

              // Unmarshal XML contents of the file myDoc.xml into your Java object

              // instance

              ObjectFactory objFac = new ObjectFactory(); // 生成Bean之后你會(huì)有這個(gè)工廠類(lèi)的

              objFac.createYourData(objFac.createYourDataType());

              BufferedInputStream bis = new BufferedInputStream(new FileInputStream("your.xml")); // 你要怎么打開(kāi)你的XML文件呢?

              JAXBElement myJAXBObject = (JAXBElement) um.unmarshal(bis); // 讀取

              YourDataType yourData = (YourDataType) myJAXBObject.getValue(); // 可以用啦

              // 下面是寫(xiě)XML的例子

              Marshaller m = jc.createMarshaller();

              m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

              File outfile = new File("yourOutput.xml");

              BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outfile), 4096);

              m.marshal(myJAXBObject, bos); // 一步寫(xiě)入。 myJAXBObject 需要你自己構(gòu)建,你要存什么呢

              try {

              bos.flush();

              } catch (IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

              } finally {

              try {

              bos.close();

              } catch (Exception e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

              }

              }

              你也許意識(shí)到問(wèn)題了:這一下子把XML Load到內(nèi)存里,你是不是瘋了?為了避免瘋掉,你可以用Satx啊,那玩意兒不是流式的么?給個(gè)栗子,讀取這樣的XML文件片段:

              <OutXMLData>
              <SubXMLItemType>
              …
              </SubXMLItemType>
              <SubXMLItemType>
              …
              </SubXMLItemType>
              <SubXMLItemType>
              …
              </SubXMLItemType>
              …
              </OutXMLData>

              private static void readWriteWithStAXAndJAXB() throws FactoryConfigurationError, FileNotFoundException, XMLStreamException, UnsupportedEncodingException, JAXBException,

              PropertyException {

              // set up a StAX reader

              XMLInputFactory xmlif = XMLInputFactory.newInstance();

              BufferedInputStream bis = new BufferedInputStream(new FileInputStream("inputLarge.xml"));

              XMLStreamReader xmlr = xmlif.createXMLStreamReader(bis);

              File outfile = new File("output\outfile.xml");

              OutputStreamWriter bos = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8");

              XMLOutputFactory xmlof = XMLOutputFactory.newInstance();

              XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(bos);

              xmlw.writeStartDocument("UTF-8", "1.0");

              xmlw.writeStartElement("OutXMLData");

              JAXBContext ucontext = JAXBContext.newInstance(SubXMLItemType.class);

              Unmarshaller unmarshaller = ucontext.createUnmarshaller();

              Marshaller marshaller = ucontext.createMarshaller();

              marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

              marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

              xmlr.nextTag();

              xmlr.require(XMLStreamConstants.START_ELEMENT, null, "OutXMLData");

              xmlr.nextTag();

              int iCount = 0;

              while (xmlr.getEventType() == XMLStreamConstants.START_ELEMENT) { // 按標(biāo)簽流式讀取

              iCount++;

              JAXBElement pt = unmarshaller.unmarshal(xmlr, SubXMLItemType.class); // 只讀取映射SubItem的內(nèi)容

              marshaller.marshal(pt, xmlw); // 這步是分批流式寫(xiě)入

              xmlw.writeCharacters(" ");

              if (xmlr.getEventType() == XMLStreamConstants.CHARACTERS) {

              xmlr.next();

              }

              }

              xmlw.flush();

              xmlw.writeEndElement();

              xmlw.writeEndDocument();

              System.out.println("Entity Count is :" + iCount);

              xmlr.close();

              xmlw.close();

              }

              說(shuō)完這么多,基本上用Java處理XML已經(jīng)不是難事了。不過(guò),有時(shí)候你會(huì)有:給你蟹八件兒,你也無(wú)從下嘴的感受。比如,解析XML你可以掌控,隨便你用啥,可是你調(diào)用的下游程序接口卻需要另外一種格式的數(shù)據(jù)。比如,你用Stax解析XML,下游要DOM接口會(huì)不會(huì)令你抓狂起來(lái)?心里咒罵,倒霉玩意兒,你們還有沒(méi)有點(diǎn)上進(jìn)心?!最近我就遇到這事了,解析一個(gè)大的XML,下游要Sub的XML,或者叫XML片段,或者叫分割XML文件。好么,我把數(shù)據(jù)都拆成Java的Object,然后再給你拼成一個(gè)個(gè)小的XML文件發(fā)過(guò)去,喪心病狂么這不?!你如果真這么做了,就別往下看了,你會(huì)哭的!

              Java 的XML包下面有個(gè)transform的子包,看看里面會(huì)有驚喜的。可以用這個(gè)工具包幫你完成類(lèi)似的轉(zhuǎn)換,比如Stax 和 Sax 或者Dom 互相的變換。或者變換成Stream.

              拿我這個(gè)分割XML的小栗子來(lái)說(shuō):

              XMLInputFactory xif = XMLInputFactory.newInstance();

              XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml")); // 用Stax讀取XML

              xsr.nextTag(); // Advance to statements element

              TransformerFactory tf = TransformerFactory.newInstance();

              Transformer t = tf.newTransformer();

              t.setParameter(OutputKeys.OMIT_XML_DECLARATION, "no");

              t.setParameter(OutputKeys.STANDALONE, "yes");

              long i = 0;

              String action = null;

              while (xsr.hasNext()) {

              if (xsr.next() == XMLStreamConstants.START_ELEMENT) {

              if ("ContentItem".equals(xsr.getLocalName())) {

              action = getAttributeValue(xsr, "action");

              } else if ("Data".equals(xsr.getLocalName())) {

              File file = new File("out/" + action + i++ + ".xml");

              t.transform(new StAXSource(xsr), new StreamResult(file)); // 流式變換,走你~

              // DOMResult dr = new DOMResult(); // 如果你要Dom格式的,releaseMe

              // t.transform(new StAXSource(xsr), dr);

              }

              }

              }

              知道最變態(tài)的是什么嗎?需要解析XML整個(gè)內(nèi)容到String里面,不單單是數(shù)據(jù),就是整個(gè)XML標(biāo)簽和數(shù)據(jù)。其實(shí)就是ouputStream轉(zhuǎn)String的過(guò)程:

              ByteArrayOutputStream baos = new ByteArrayOutputStream();

              t.transform(new StAXSource(xsr), new StreamResult(baos));

              String subXMLStr = baos.toString();