Announcement Announcement Module
Collapse
No announcement yet.
Fix to Unmarshall a DOM tree with Castor Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Fix to Unmarshall a DOM tree with Castor

    Not sure if someone has posted this workaround before, but I didn't see anything after a quick search on "Castor"...

    Anyway, using Castor to unmarshall an XML request payload may fail if namespaces are declared outside of the payload (such as on a SOAP envelope). To work around the issue, you can extend the CastorMarshaller class and override the following method:

    Code:
        private static final String XMLNS_NS = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
        
        protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException {
            
            Node node = domSource.getNode();
            if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)node;
                
                Node parent = node.getParentNode();
                while (parent != null) {
                    NamedNodeMap atts = parent.getAttributes();
                    if (atts != null) {
                        for (int i=0, j=atts.getLength(); i<j; i++) {
                            
                            Attr att = (Attr) atts.item(i);
                            if (XMLNS_NS.equals(att.getNamespaceURI())) {
                                String name = att.getName();
                                String value = att.getValue();     
                                if (!element.hasAttributeNS(XMLNS_NS, name)) {
                                    }
                                    element.setAttributeNS(XMLNS_NS, name, value);
                                }
                            }
                            
                        }
                    }
                    parent = parent.getParentNode();
                }
            }
            
            return super.unmarshalDomSource(domSource);
        }
Working...
X