ฉันมี XML ตามที่ระบุด้านล่าง ฉันต้องการลบแท็กว่างออกจากแท็กเดิมซ้ำๆ เช่นเดียวกับใน เมื่อแท็ก f ถูกลบ แท็ก e ควรถูกลบ และเมื่อแท็ก e ถูกลบ แท็ก d จะว่างเปล่า และด้วยเหตุนี้ ควรจะลบด้วยเช่นกัน
<Test>
<a>test</a>
<b>test</b>
<c></c>
<d>
<e>
<f> </f>
</e>
</d>
</Test>
ผลลัพธ์ควรจะเป็น
<Test>
<a>test</a>
<b>test</b>
</Test>
ฉันสามารถลบแท็กได้ แต่ฉันไม่สามารถลบแท็กได้เนื่องจากมีช่องว่าง แม้ว่าฉันจะสามารถระบุได้ว่านี่เป็นแท็กที่จะลบ แต่เมื่อฉันเรียกใช้ RemoveChild() บนพาเรนต์ แท็กนั้นจะไม่ถูกลบออกจาก XML ในโค้ดขณะทำการดีบั๊ก มันจะแสดงจำนวนลูกของ e หลังจากเรียกใช้ RemoveChild() เป็นศูนย์ แต่มันยังคงอยู่ใน xml??
โปรดช่วยฉันด้วยว่าฉันทำอะไรผิด
กรุณาค้นหารหัสของฉันด้านล่างที่ฉันใช้
for (Element childElement : toRemove) {
Node parentNode = childElement.getParentNode();
System.out.println("Removing null or empty node :: " + childElement.getNodeName());
if(parentNode!=null){
NodeList childList = parentNode.getChildNodes();
System.out.println("List of Childer before deleting :: " + childList.getLength());
parentNode.removeChild(childElement);
clean(parentNode);
childList = parentNode.getChildNodes();
int childCount = childList.getLength();
for (int i = 0; i < childCount; i++) {
Node childNode = childList.item(i);
System.out.println("Childs :: " + childNode);
}
for (int i = 0; i < childCount; i++) {
Node childNode = childList.item(i);
if(childNode!=null){
System.out.println("Child before deleting :: " + childNode);
if (childNode instanceof Element == false){
if(childNode.getNodeValue().trim().isEmpty()){
System.out.println("found unwanted :: " + childNode.getNodeName());
parentNode.removeChild(childNode);
i--;
childCount--;
clean(parentNode);
}
}
}
}
childList = parentNode.getChildNodes();
System.out.println("List of Childer after deleting :: " + childList.getLength());
}
}