Reputation: 203
How can I find and delete item id="s2" using Java DOM parser?
<manifest>
<item href="html/section1.html" id="s1" media-type="application/xhtml+xml"/>
<item href="html/section2.html" id="s2" media-type="application/xhtml+xml"/>
<item href="html/section3.html" id="s3" media-type="application/xhtml+xml"/>
</manifest>
I use this code but return Null
Node metadataXML = doc.getElementsByTagName("manifest").item(0);
NodeList list = metadataXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
list.item(i).getAttributes().removeNamedItem("s2");
}
Upvotes: 2
Views: 3138
Reputation: 3377
Here is the code to do it in vtd-xml, instead of DOM, you can find quite a few refereces on SO, even its own tag...
import com.ximpleware.*;
public class deleteNode {
public static void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
ap.selectXPath("/*/*[@id='s2']");// this is the key XPath expression
int i=0;
while((i=ap.evalXPath())!=-1){
xm.remove(vn.getElementFragment());// remove the node
}
xm.output("new.xml"); // output to a new document called new.xml
}
}
Upvotes: 0
Reputation: 203
I find difference way in this links comment and worked
NodeList nList = doc.getElementsByTagName("item");
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("s" + index)) {
System.err.println("sdsd");
node.getParentNode().removeChild(node);
}
}
}
Upvotes: 1
Reputation: 404
Look at this answer: Removing DOM nodes when traversing a NodeList
You have to use something like:
Node metadataXML = doc.getElementsByTagName("manifest").item(0);
NodeList list = metadataXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Element manifestItem = (Element) list.item(i);
if ("s2".equals(manifestItem.getAttribute("id"))) {
metadataXML.removeChild(manifestItem);
}
}
Upvotes: 0