正 文

用 AXIOM 促进 XML 处理


www.7dspace.com  更新日期:2005-10-26 2:35:01  七度空间


      输出

      现在可以使用 StAX writer 来序列化构造好的元素:

      清单 3.序列化 line item

   XMLOutputFactory xof = XMLOutputFactory.newInstance();
   XMLStreamWriter writer = xof.
      createXMLStreamWriter(System.out);
      lineItem.serialize(writer);
      writer.flush();

      从已有代码构造 AXIOM

      现在看看相反的过程,从数据流建立内存对象模型。

      最简单的情况下,只需要关心 XML 片段的反序列化。但是在 SOAP 处理中,需要反序列化 SOAP 消息或者经过 MTOM 优化的 MIME 信封。因为与 SOAP 处理关系特别密切,所以 AXIOM 为此提供内置支持,稍候将详细介绍。但首先要说明如何反序列化简单的 XML 片段,具体来说就是刚刚序列化的那个 XML 片段。

       首先构造一个解析器。AXIOM 支持用 SAX 和 StAX 解析器解析 XML。但是,SAX 解析不允许对象模型的延迟构造,因此在延迟构建很重要时,应该使用基于 StAX 的解析器。

       第一步是为数据流获得一个 XMLStreamReader:

File file= new File("line-item.xml");
         FileInputStream fis= new FileInputStream(file);
         XMLInputFactory xif= XMLInputFactory.newInstance();
         XMLStreamReader reader= xif.createXMLStreamReader(fis);

       然后创建一个 builder 并将 XMLStreamReader 传递给它:

   StAXOMBuilder builder= new StAXOMBuilder(reader);
         lineItem= builder.getDocumentElement();

      现在可以使用 AXIOM API 来访问属性和子元素或者 XML Infoset 项了。可以这样访问属性:

   OMAttribute quantity= lineItem.getFirstAttribute(
         new QName("http://openuri.org/easypo", "quantity"));
   System.out.println("quantity= " + quantity.getValue());

      用类似的方式访问子元素:

   price= lineItem.getFirstChildWithName(
         new QName("http://openuri.org/easypo", "price"));
               System.out.println("price= " + price.getText());

      清单 4 显示了完整的代码片段。

7页,页码:[1] [2] [3] [4] [5] [6] [7] 

上一篇:用JAXB生成一个XML文档
下一篇:架设局域网升级服务器 用WSUS打补丁
作者:Eran Chinthaka  来源:developerWorks中国 ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐