简体   繁体   English

无法解析xml条目

[英]Can't parse xml entry

Xml has an entry like: Xml的条目如下:

<News:Source>AD HOC News</News:Source>

But when using stax xml parser it ignores that line: 但是,当使用stax xml解析器时,它将忽略该行:

    static final String SOURCE = "News:Source";
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    // Setup a new eventReader
    InputStream in = read();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
    // read the XML document
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                String localPart = event.asStartElement().getName().getLocalPart();
                    switch (localPart) {
                    ...
                        case SOURCE:
                            // System.out.println("nothing happens here");
                            source = getCharacterData(event, eventReader);
                            break;
                    ...

What is the reason? 是什么原因?

It is usually a bad idea to use the namespace prefix ("News") in code destined to identify an XML element. 在用于标识XML元素的代码中使用名称空间前缀(“新闻”)通常是一个坏主意。 The prefix is defined somewhere in the XML file, and completely independent from the actual namespace identifier. 前缀在XML文件中的某个位置定义,并且完全独立于实际的名称空间标识符。

A correct identification must make use of QName. 正确的标识必须使用QName。

If all elements are from the same namespace you may get away with using the local name alone ("Source"), but one would have to know all about the XML file to be able to guarantee that. 如果所有元素都来自同一个命名空间,则您可能会只使用本地名称(“源”)就可以摆脱困境,但是您必须完全了解XML文件才能保证这一点。

Later Well, this last proposal is what you were already doing in your code. 后来 ,最后一条建议就是您在代码中已经在做的事情。 Thus, just use 因此,只需使用

static final String SOURCE = "Source";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM