Search code examples
javaxmlstax

Can't parse xml entry


Xml has an entry like:

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

But when using stax xml parser it ignores that line:

    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?


Solution

  • It is usually a bad idea to use the namespace prefix ("News") in code destined to identify an XML element. The prefix is defined somewhere in the XML file, and completely independent from the actual namespace identifier.

    A correct identification must make use of 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.

    Later Well, this last proposal is what you were already doing in your code. Thus, just use

    static final String SOURCE = "Source";