Search code examples
javaxmlxstream

Parsing XML node's attribute with prefixes - XSTREAM/JAVA


I'm using StaxDriver with XStream and trying to parse this XML:

<cad:MyObj xmlns:cad="namespace" cad:testeId="873" >
  <cad:node1>value node 1</cad:node1>
</cad:MyObj>

into an object.

I can parse node1 with the prefix but I don't know how to configure XStream with Stax to use the prefix cad with atributes (testeId).

Here's my conf:

QNameMap qnameMap = new QNameMap(); 
            qnameMap.setDefaultPrefix("cad");
            qnameMap.setDefaultNamespace("namespace");
            StaxDriver stax = new StaxDriver(qnameMap);
            stax.getInputFactory().setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
            stax.setRepairingNamespace(true);
            stax.setQnameMap(qnameMap);
            xstream = new XStream(stax); 
            xstream.alias("MyObj", MyObj.class);
            xstream.useAttributeFor(MyObj.class, "testeId");

I've tried to "cheat" with this:

xstream.aliasField("cad:testeId", ProdutoVersao.class, "testeId");

but didn't work =/

Hope someone know how to do it.


Solution

  • Well. I think there is no solution for this using XStream.

    I've changed to JAXB with a namespace prefix mapper:

    http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html

    Marshaller m = context.createMarshaller();
    ProdutoVersaoPrefixMapper mapper = new ProdutoVersaoPrefixMapper();
    m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", mapper);
    

    With this code the node and his attributes get the prefix.