无法在SAX DefaultHandler的startElement()方法中打印localname

时间:2015-06-20 17:20:57

标签: sax

import java.io.FileInputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Sample1SAX {

    /**
     * @param args
     * @throws SAXException
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        SAXParserFactory myFactory = SAXParserFactory.newInstance();
        SAXParser sp = myFactory.newSAXParser();

        MyHandler sh = new MyHandler();
        sp.parse(new FileInputStream("test.xml"), sh);

    }

}

class MyHandler extends DefaultHandler {

    public void startDocument() {
        System.out.println("XML document parsing started.");
    }

    public void endDocument() {
        System.out.println("XML document parsing ended");
    }

    public void startElement(String namespaceURI, String localName,
            String qName, Attributes attrs) {

        System.out.println(localName + "+++++++++++++++++++++++++++");
        System.out.println("QName is " + qName);

    }

}

使用以下xml文件

运行此程序后
<?xml version="1.0" encoding="UTF-8"?>
<mybook:book xmlns:mybook="http://www.test.mm/books">
    <mybook:title>Java Exercise Book</mybook:title>
    <mybook:price>$3000</mybook:price>
    <mybook:author xmlns:people="http://www.test2.mm/person">
        <person:name>myname</person:name>
        <person:title>AAA</person:title>

    </mybook:author>


</mybook:book>

我的输出是 XML文档解析已开始。 的 +++++++++++++++++++++++++++ QName是mybook:book 的 +++++++++++++++++++++++++++ QName是mybook:title 的 +++++++++++++++++++++++++++ QName是mybook:价格 的 +++++++++++++++++++++++++++ QName是mybook:author 的 +++++++++++++++++++++++++++ QName是person:name 的 +++++++++++++++++++++++++++ QName是person:title XML文档解析已结束

根据此输出虽然可以打印QName,但我无法打印localName。我想知道为什么我不能打印localName。

1 个答案:

答案 0 :(得分:0)

现在我知道如何打印localName。 我在创建SAXParserFactory实例后插入以下语句,如下所示:

SAXParserFactory myFactory = SAXParserFactory.newInstance(); myFactory.setNamespaceAware(true);

我的输出是:

开始XML文档解析。

图书+++++++++++++++++++++++++++ QName是mybook:book

<强>标题+++++++++++++++++++++++++++ QName是mybook:title

<强>价+++++++++++++++++++++++++++ QName是mybook:price

<强>作者+++++++++++++++++++++++++++ QName是mybook:author