StAX

Streaming API for XML (StAX) is an application programming interface (API) to read and write XML documents, originating from the Java programming language community.

下面是IBM的关于StAX的文章,大家可以参考一下。

http://www.ibm.com/developerworks/library/x-stax1/index.html


然后是一个简单的例子。

以下面这个xml为例:

<?xml version="1.0"?>
<company>
    <staff>
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
        <salary1>111111</salary1>
    </staff>
    <staff>
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </staff>
</company>


代码:

从代码中可以看到StAX并没有使用什么特殊类。

package markey.testng;


import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

/**
 * This program demonstrates how to use a StAX parser. The program prints all
 * hyperlinks links of an XHTML web page. <br>
 * Usage: java StAXTest url
 *
 * @author Cay Horstmann
 * @version 1.0 2007-06-23
 */
public class STAXTesting {
    public static void main(String[] args) throws Exception {
        InputStream in = new FileInputStream("d:/book/file.xml");
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(in);

        boolean dosStart = false;
        String doc = "

       

       //StAX提供了这个迭代器,通过wrap这个迭代器,我们可以方便的控制什么时候读取XML的下一行。

        while ( parser.hasNext()) {
            int event = parser.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                if (parser.getLocalName().equals("staff")) {
                    dosStart = true;
                    doc = "";
                    continue;
                }
            }else if (event == XMLStreamConstants.END_ELEMENT) {
                    if (parser.getLocalName().equals("staff")) {
                        dosStart = false;
                        System.out.println(doc);
                        continue;
                    }
            }

            if (dosStart == true && event == XMLStreamConstants.START_ELEMENT) {
                        doc += parser.getLocalName() + ":"
                                + parser.getElementText() + ";";
                        continue;
            }
    }
}
}

你可能感兴趣的:(exception,xml,XHTML,String,application,interface)