0

I'm using javax.xml.stream.XMLInputFactory to parse an XML file, but I have trouble parsing the namespace.

In the first line of the XML a namespace is defined

<iati-activities xmlns:akvo="http://akvo.org/iati-activities" version="2.01" generated-datetime="2016-03-29T07:18:39Z">

I'm trying to decode using the following snippet

int theType = theReader.next();
switch (theType) {
    case XMLStreamConstants.START_ELEMENT:
        String theLocalName = theReader.getLocalName();
        if (theLocalName.equalsIgnoreCase(IatiLabel.IATIACTIVITIES.getLabel())) {
            for (int i = 0; i < theReader.getAttributeCount(); i++) {
                System.out.println("Localname: " + theReader.getAttributeLocalName(i));
                System.out.println("Namespace: " + i + " = " + theReader.getAttributeNamespace(i));
                System.out.println("Attr value: " + theReader.getAttributeValue(i));
//              System.out.println("Prefix: " + theReader.getNamespacePrefix(i));
                System.out.println("URI: " + theReader.getNamespaceURI(i));
            }

            System.out.println("URI 2: " + theReader.getPrefix());
    }
}

The result is:

Localname: version
Namespace: 0 = null
Attr value: 2.01
URI: http://akvo.org/iati-activities
Localname: generated-datetime
Namespace: 1 = null
Attr value: 2016-03-29T07:18:39Z
URI: null
URI 2: 

If I un-comment the theReader.getNamespacePrefix() line I get a null pointer exception.

The rest of the XML file parses just fine, but I need to know the namespace prefix for a certain part.

Any idea what I'm doing wrong?

  • This is probably a duplicate of http://stackoverflow.com/questions/5416637/how-to-get-xmlnsxxx-attribute-if-set-setnamespaceawaretrue-in-sax – gustf Mar 29 '16 at 11:35
  • I'll check that answer out. Thank you. – Mirko Pelgrom Mar 29 '16 at 11:40
  • It was not exactly the same, but it helped my find a solution. Thanks – Mirko Pelgrom Mar 30 '16 at 09:55
  • Cool, if it wasn't the same it might be an idea to add an answer to the question so others with the same problem can see :) – gustf Mar 30 '16 at 10:59
  • 1
    I would like to, but the solution was simply go about the problem in a completely different way. When I learned that XMLInputFactory doesn't offer this functionality, I went looking for an answer in another direction. I do know where the file comes from, therefore I do know if a namespace will be there. It is a sub-par solution, but the XML parser will only be used during a migration, so it does suffice. – Mirko Pelgrom Mar 30 '16 at 12:17

0 Answers0