I have an dynamic XML that needs to be transformed based on the values of its XML. The group nodes with an attribute type="newNode"
needs to be removed because they are already derived.
I tried the following:
Create new nodes based on the XML and delete the unnecessary nodes but I encountered an issue when using
doc.removeChild(node)
sayingException in thread "main" org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
NodeList nodeList = doc.getElementsByTagName(NODE_MAPPINGS_NODE); for (int i = 0; i < nodeList.getLength(); i++) { Node nodeToBeRemoved = nodeList.item(i); if (nodeToBeRemoved.getNodeType() == Node.ELEMENT_NODE) { doc.getDocumentElement().removeChild(nodeToBeRemoved); } }
Created a new document based on the original document but I encountered an error saying
Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
NodeList nodeList = doc.getElementsByTagName(NODE_MAPPINGS_NODE); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if(!node.hasAttributes()) { Element elem = newDoc.createElement(node.getNodeName()); newDoc.appendChild(elem); } } }
Here is the sample XML that I am trying to parse:
<root>
<input>
<nodeMappings type="newNode">
<name>declarationType</name>
<type>derived</type>
<derivedValue>X</derivedValue>
</nodeMappings>
<nodeMappings type="newNode">
<name>identificationNumber</name>
<type>derived</type>
<derivedValue>5000000612</derivedValue>
</nodeMappings>
<characteristicsOfTaxPayer>
<nodeMappings type="newNode">
<name>collectivePerson</name>
<type>derived</type>
<derivedValue>X</derivedValue>
</nodeMappings>
</characteristicsOfTaxPayer>
<listTest>
<nodeMappings type="newNode">
<name>primaryKey</name>
<type>derived</type>
<derivedValue>1</derivedValue>
</nodeMappings>
<nodeMappings type="newNode">
<name>value</name>
<type>derived</type>
<derivedValue>test1</derivedValue>
</nodeMappings>
</listTest>
<listTest>
<nodeMappings type="newNode">
<name>primaryKey</name>
<type>derived</type>
<derivedValue>2</derivedValue>
</nodeMappings>
<nodeMappings type="newNode">
<name>value</name>
<type>derived</type>
<derivedValue>test2</derivedValue>
</nodeMappings>
</listTest>
</input>
</root>
After processing it should look like this:
<root>
<input>
<declarationType>X</declarationType>
<identificationNumber>5000000612</identificationNumber>
<characteristicsOfTaxPayer>
<collectivePerson>X</collectivePerson>
</characteristicsOfTaxPayer>
<listTest>
<primaryKey>1</primaryKey>
<primaryKey>test1</primaryKey>
</listTest>
<listTest>
<primaryKey>2</primaryKey>
<primaryKey>test2</primaryKey>
</listTest>
</input>
</root>
Is there a better way to do this?