Cannot get attribute on xml with namespace

44 views Asked by At

I am running into trouble with jOOX when trying to get an attribute and with other xpath expressions. This is with a schema that I cannot change.

With vast 3.0 there is no targetNamespace so the xml looks like this.

<VAST version="3.0">
            
</VAST>

But with vast 4.2 there is a targetNamespace so the namespace declaration is required.

<VAST version="4.2" xmlns="http://www.iab.com/VAST">
            
</VAST>

If I try to get the version attribute for 3.0 this works.

var vast3version = $("""
    <VAST version="3.0">
            
    </VAST>
    """).xpath("/VAST").attr("version");

assertThat(vast3version).isEqualTo("3.0");

But if I try vast 4.2 it returns null and the test fails.

var vast42version = $("""
    <VAST version="4.2" xmlns="http://www.iab.com/VAST">
            
    </VAST>
    """).xpath("/VAST").attr("version");

assertThat(vast42version).isEqualTo("4.2");

It looks like the introduction of a namespace causes an issue and I'm not sure how to get around it. I'm trying to write an editor class to modify the xml and support both versions but none of the xpaths work for vast 4.2 xml.

Is there a way to get the version that works for both xml inputs?

1

There are 1 answers

0
John Mercier On

jOOX builds the document with setNamespaceAware(true) this causes the document to use namespaces which then requires xpath expressions to use namespaces.

This can be fixed by building the document manually with a the DocumentBuilderFactory and passing it to jOOX. Don't call setNamespaceAware(true).

var domFactory = DocumentBuilderFactory.newInstance();
var builder = domFactory.newDocumentBuilder();
var document = builder.parse(new ByteArrayInputStream("""
    <VAST version="4.2" xmlns="http://www.iab.com/VAST">
            
    </VAST>
    """.getBytes()));
var vast42version = $(document).xpath("/VAST").attr("version");

assertThat(vast42version).isEqualTo("4.2");