---
title: "Java XML解析之 StAX"
author: "softstone"
date: "2008-01-24T18:02:00Z"
tags: []
slug: "java-xml-stax"
draft: false
lastmod: "2008-01-24T18:02:00Z"
id: 172898
url: "https://softstone.iteye.com/blog/172898"
---

StAX：Streaming API for XML ，如同字面意思，是基于流的API，相对于传统的DOM和SAX，StAX在性能和易用性上取得了很好的平衡。StAX是基于SAX的，同样将XML作为一组事件来处理，不过与SAX不同的是，StAX是采用拉（Pull）的方式来处理事件， 允许应用程序从事件流中拉出事件，而不是提供从解析器中接收事件的回调程序程序。

StAX 包括两套处理 XML 的 API，分别提供了不同程度的抽象。一种是基于指针的 API， 提供应用程序把 XML 作为一个标记（或事件）流来处理，这是一种低层 API，效率高，抽象程度低。另一种是较为高级的基于迭代器的 API， 提供应用程序把 XML 作为一系列事件对象来处理，每个对象和应用程序交换 XML 结构的一部分，应用程序直接处理这些代表了XML结构一部分的事件对象。

StAX在JDK6中已经内置了，或许就是以后的标准。

下面以一个简单的例子示范基于指针的API的使用。例子说明：从一个xml结构的订单信息中parse出Java对象，修改这个对象，然后输出为一个xml文件。

**一、xml文件内容**

 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;!DOCTYPE po SYSTEM "src/sample.dtd"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;po id="po121" submitted="2001-10-05"  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    xmlns="http://www.csdn.net"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    &lt;billTo id="addr-1"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;company&gt;The Redzero Cop.&lt;/company&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;street&gt;Jianguo Road 1ST&lt;/street&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;street&gt;Building 1&lt;/street&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;city&gt;Haidian&lt;/city&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;state&gt;Beijing&lt;/state&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;postalCode&gt;100071&lt;/postalCode&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    &lt;/billTo&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    &lt;shipTo href="addr-1"/&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    &lt;order&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;item sku="o318-BP" quantity="5"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)            &lt;description&gt;J2EE programmic&lt;/description&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;/item&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;item sku="o947-TI" quantity="12"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)            &lt;description&gt;Java WEB Service&lt;/description&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;/item&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;item sku="o008-PR" quantity="133"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)            &lt;description&gt;C++ develop&lt;/description&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)        &lt;/item&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    &lt;/order&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;/po&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)

**二、Java对象结构** 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)public class Order  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    List items = new ArrayList();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public void addItem(Item item)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        items.add(item);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    @Override  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public String toString()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        StringBuffer buf = new StringBuffer();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        buf.append("order ");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        for (Iterator itr = items.iterator();itr.hasNext();)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            Item item = (Item)itr.next();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            buf.append("item ");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            buf.append("sku=").append(item.getSku()).append(" ").append("quantity=").append(item.getQuantity()).append(" ")  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            .append("description=").append(item.getDescription()).append(" ");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return buf.toString();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)public class Item  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    String sku;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    int quantity;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    String description;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public String getDescription()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return description;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public void setDescription(String description)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        this.description = description;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public int getQuantity()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return quantity;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public void setQuantity(int quantity)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        this.quantity = quantity;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public String getSku()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return sku;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public void setSku(String sku)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        this.sku = sku;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

**三、解析示例，注意代码注释**

**解析**

 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * 解析XML文档，把数据绑定到Java对象上  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @param in  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @return  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    public Order parse(InputStream in)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        Stack stack = new Stack();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        try  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //1.得到XMLStreamReader  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            XMLInputFactory inputFactory = XMLInputFactory.newInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            XMLStreamReader reader = inputFactory.createXMLStreamReader(in);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            while (reader.hasNext())  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)            ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                //2.根据事件类型做相应的处理，对于多数应用来说，处理完成可以直接break，跳出循环，提高性能  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                switch (reader.getEventType())  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)                ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                case XMLStreamReader.START\_ELEMENT:  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                    String name = reader.getLocalName();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                    if ("order".equals(name))  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)                    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        Order order = new Order();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        stack.push(order);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)                    } else if ("item".equals(name))  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)                    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        Item item = new Item();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        String sku = reader.getAttributeValue(0);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        String quantity = reader.getAttributeValue(1);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        item.setSku(sku);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        item.setQuantity(Integer.parseInt(quantity));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        stack.push(item);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)                    } else if ("description".equals(name))  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)                    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        String desc = reader.getElementText();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        Item item = (Item) stack.pop();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        item.setDescription(desc);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        Order order = (Order) stack.peek();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                        order.addItem(item);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)                    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                    break;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)                }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                reader.next();//获取下一个解析事件  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        } catch (XMLStreamException e)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{              
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if (!stack.empty())  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            return (Order) stack.pop();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        } else  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            return null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)

**输出**

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)