【问题标题】:Why can't I open this XML in SAXParser?为什么我不能在 SAXParser 中打开这个 XML?
【发布时间】:2011-01-16 01:56:38
【问题描述】:
public static void parseit(String thexml){
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser;

    try {
        saxParser = factory.newSAXParser();
        DefaultHandler handler = new DefaultHandler() {
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            }
            public void endElement(String uri, String localName, String qName)throws SAXException {

            }           
            public void characters(char ch[], int start, int length) throws SAXException {

            }               
         };      
        saxParser.parse(thexml, handler);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("e", "e", e);
            e.printStackTrace();
        }catch (ParserConfigurationException e) {
            e.printStackTrace();    
        }
}

这是我的代码。 (非常感谢这些人:Can someone help me with this JAVA SAXParser?

问题是,我总是遇到 IOException e。消息是这样的:

java.io.IOException: Couldn't open....and then my XML file.

我的 XML 文件是这样的,它是一个字符串

<?xml version="1.0" encoding="UTF-8"?>
<result>
    <person>
        <first_name>Mike</first_name>
    </person>
</result>

为什么它不能读取我的 XML 字符串?

【问题讨论】:

    标签: java xml debugging exception parsing


    【解决方案1】:

    您调用的parse 方法需要一个指向要读取的 XML 文件的 URI。

    您可能想要做的是从StringReader 创建一个InputSource,如下所示:

    InputSource source = new InputSource(new StringReader(thexml));
    saxParser.parse(source, handler);
    

    【讨论】:

      【解决方案2】:

      SAXParser 的 parse 方法需要文件名或 URI 作为第一个参数,而不是读入字符串的 XML 文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多