How to delete node from xml based on attribute using java with DOM Parser

心不动则不痛 提交于 2019-12-11 04:10:55

问题


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.


回答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();
                      }


来源:https://stackoverflow.com/questions/9532519/how-to-delete-node-from-xml-based-on-attribute-using-java-with-dom-parser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!