1

I want to delete a node from XML file based on attribute using JAVA with DOM Parser. For Example

<company>
    <staff id="1">
        <firstname>yong</firstname>

    </staff>
    <staff id="2">
        <firstname>low</firstname>

    </staff>
</company>

Based on staff id,i want to delete node.

3
  • 1
    I have tried following code after doing all docummentBuilder API. NodeList nList = doc.getElementsByTagName("staff"); for (int i = 0; i < nList.getLength(); i++) { Node node=nList.item(i); if (node.getNodeType()==Element.ELEMENT_NODE) { Element eElement=(Element) node; System.out.println(eElement.getAttribute("id")); if (eElement.getAttribute("id").equals("1")) { System.err.println("sdsd"); node.getParentNode().removeChild(node); } } } Commented Mar 2, 2012 at 11:51
  • And - what happens? Do you get an exception or is the removed node still in the DOM? Commented Mar 2, 2012 at 11:58
  • No Exception.Node is still there in DOM. Commented Mar 3, 2012 at 5:12

1 Answer 1

1

Thanks for reply. Above solution which i posted is correct.Only i need to write xml again with some transform API. Posting solution,if any body has the same problem.

try{
                            //Save the Created XML on Local Disc using Transformation APIs as Discussed
                            TransformerFactory tFactory = TransformerFactory.newInstance();
                            Transformer transformer = tFactory.newTransformer();
                            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                            Source s = new DOMSource(doc);
                            Result res = new StreamResult( new FileOutputStream(fXmlFile));
                            try {
                                transformer.transform(s, res);
                            } catch (TransformerException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        } catch(TransformerConfigurationException e)
                        {
                            e.printStackTrace();
                        }
                      } catch (Exception e) {
                        e.printStackTrace();
                      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.