How to remove a node in XML using JAVA



The XML file I use is like this, pay attention that there are 4 'target' tag.



<?xml version="1.0" encoding="UTF-8" standalone="no"?><project basedir="." default="end" name="precompile">
<property name="charset" value="utf-8"/>

<target name="start">
</target>

<target depends="precompile-templates1,precompile-templates2" name="end">
<echo>finish generating precompiled templates</echo>
</target>



<target name="precompile-templates1">
<property name="outputJS1" value="jsp/jsp_2/js/templates.js"/>
<property name="templatesPath1" value="jsp/jsp_2/js/tmpl"/>

<java dir="${basedir}" failonerror="true" fork="true" jar="lib/js.jar">
<arg value="otherFiles/lib/rhino-handlebars-compiler.js"/>
<arg value="--handlebars"/>
<arg value="otherFiles/third-party/handlebars-v1.3.0.js"/>
<arg value="--templates"/>
<arg value="${templatesPath1}"/>
<arg value="--output"/>
<arg value="${outputJS1}"/>
</java>
<echo>Template Precompiled to web/js/compiled-templates.js</echo>
<echo> is now ready to compress....</echo>
</target>

<target name="precompile-templates2">
<property name="outputJS2" value="jsp/jsp_3/js/templates.js"/>
<property name="templatesPath2" value="jsp/jsp_3/js/tmpl"/>

<java dir="${basedir}" failonerror="true" fork="true" jar="lib/js.jar">
<arg value="otherFiles/lib/rhino-handlebars-compiler.js"/>
<arg value="--handlebars"/>
<arg value="otherFiles/third-party/handlebars-v1.3.0.js"/>
<arg value="--templates"/>
<arg value="${templatesPath2}"/>
<arg value="--output"/>
<arg value="${outputJS2}"/>
</java>
<echo>Template Precompiled to web/js/compiled-templates.js</echo>
<echo> is now ready to compress....</echo>
</target></project>


I want to keep the first 2 'target' node but remove the rest 2 nodes of 'target'. What should I do? I was trying to do something like this:



File fXmlFile = new File(subBuildFile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

Node s = doc.getElementsByTagName("target").item(1);

for(int i =2; i<doc.getElementsByTagName("target").getLength();i++){
doc.getElementsByTagName("target").item(i).removeChild(doc.getElementsByTagName("target").item(i));
}


But there always is a similar error like this:



Exception 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.
at com.sun.org.apache.xerces.internal.dom.ParentNode.internalRemoveChild(Unknown Source)
at com.sun.org.apache.xerces.internal.dom.ParentNode.removeChild(Unknown Source)
at xmlReader.Test.resetXML(Test.java:52)
at xmlReader.Test.main(Test.java:39)


Any suggestion?


No comments:

Post a Comment