【问题标题】:Java use sax to parse xml files. Can't get the correct content when coming up &amp [duplicate]Java 使用 sax 来解析 xml 文件。出现时无法获得正确的内容&amp [重复]
【发布时间】:2017-08-30 12:26:57
【问题描述】:

我在使用 sax 解析 xml 文件时遇到了一些问题。

Java 内容处理程序代码如下所示:

boolean rcontent = false;

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (qName.equalsIgnoreCase("content")) {
        rcontent = true;
    }
}

@Override
public void characters(char ch[], int start, int length) throws SAXException {
    if (rcontent){
        System.out.println("content: " + new String(ch, start, length));
        rcontent = false;
    }
}

xml文件内容是这样的:

但是输出是:

我想说

这不完整。

【问题讨论】:

    标签: java xml sax


    【解决方案1】:

    对于单个 <content> 块,可能会多次调用 characters(...)。尝试类似

    StringBuilder builder;
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("content")) {
            builder = new StringBuilder();
        }
    }
    
    @Override
    public void characters(char ch[], int start, int length) throws SAXException {
        if (builder != null){
            builder.append(new String(ch, start, length));
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (builder != null) {
            System.out.println("Content = " + builder);
            builder = null;
        }
    }
    

    【讨论】:

    • 干杯!它工作得很好!但是为什么 characters(...) 会为单个标签多次调用?是因为它符合 &amp 还是它的尺寸最大?
    • 读取javadocs,其中指出字符数据已“分块”。通常这样做是为了避免在内存中不必要地使用大型字符数组。我猜不同的 sax 解析器可能会选择以不同的方式分块字符,所以你不应该依赖分块实现。
    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2016-10-15
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多