Search code examples
javaxmlxercesxalan

Getting org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR adding root node to document


I'm trying to create a simple XML document and am receiving the above error when adding the root element to the document. I only have the one root element (the first element created for the document) and the error throws on the first append_child() call. Here is the code leading up to where the error throws (on the securityDoc.appendChild(securityDoc) call):

 public Document CreateSecurityHeader() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document securityDoc = builder.newDocument();

    try {
        Element securityRoot = securityDoc.createElementNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:Security");            
        securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:env", "http://www.w3.org/2003/05/soap-envelope");
        securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wss","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        securityRoot.setAttribute("env:mustUnderstand", "1");            
        securityDoc.appendChild(securityDoc);

As this is the only Element in that document at this point, how am I getting the this error? I did have to pull in the xalan and xerces library as dependencies for this project for something else, could there be an incompatibility here?


Solution

  • Whoops. You append securityDoc to securityDoc.

    securityDoc.appendChild(securityDoc);
    

    I'm sure you mean this:

    securityDoc.appendChild(securityRoot);
    

    I only noticed this myself by stepping through the validation code and when it was using the node lookup tables to check whether the proposed tree structure is legal I saw that what you were appending was DOCUMENT_NODE, which is not legal to append to a DOCUMENT_NODE.