dom4j 删除所有节点的文本都为空的父节点

时间:2021-11-01 14:30:10

xml 如下,如果row节点的子节点的text全部为空就删除row 节点。

<?xml version="1.0" encoding="UTF-8"?>
<Project internalId="4e303a41-9e23-4193-90a9-67c8e6b44699" name="BAM Testing">
<DataTables>
<Table internalId="a16c7435-3fdc-4357-9133-df22ad235bb2" name="Data Preparation_Group">
<Columns>
<Column name="Name"/>
<Column name="Description"/>
<Column name="Grouptype"/>
</Columns>
<Rows>
<Row isEnabled="true">
<Field column="Name"></Field>
<Field column="Description"></Field>
<Field column="Grouptype"></Field>
</Row>
<Row isEnabled="true">
<Field column="Name"></Field>
<Field column="Description"></Field>
<Field column="Grouptype"></Field>
</Row>
<Row isEnabled="true">
<Field column="Name">Citibank Individuals</Field>
<Field column="Description">Citibank Individuals</Field>
<Field column="Grouptype">Individual Group</Field>
</Row>
<Row isEnabled="true">
<Field column="Name">Test_Delete</Field>
<Field column="Description">Test for Delete Function</Field>
<Field column="Grouptype">Institution Group</Field>
</Row>
<Row isEnabled="true">
<Field column="Name">Test_Edit</Field>
<Field column="Description">Test for Edit Function</Field>
<Field column="Grouptype">Institution Group</Field>
</Row>
</Rows>
</Table>
</DataTables>
</Project>


 

package xmlTest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
@SuppressWarnings("unchecked")
public class RemoveTheNodeWithEmptyText
{
public static void main(String[] args) throws DocumentException, IOException
{
removeAllNodeWithEmptyText(
"C:/Users/Administrator/Desktop/BAM Testing_Data.xml",
"//Table/Rows/Row");
}


public static void removeAllNodeWithEmptyText(String file, String xpath)
throws DocumentException, IOException
{
SAXReader reader = new SAXReader();
Document doc = reader.read(new File(file));
boolean Flag = false;
List<Element> list = new ArrayList<Element>();
// list=doc.selectNodes("//Rows/Row/@isEnabled");
// //Table[contains(name,'Data Preparation')]Rows/Row
list = doc.selectNodes(xpath);
System.out.println(list.size());
Iterator iter = list.iterator();
iter = list.iterator();

while (iter.hasNext())
{
Element bookElement = (Element) iter.next();

//
Iterator iterator = bookElement.elementIterator("Field");
while (iterator.hasNext())
{
Element titleElement = (Element) iterator.next();
if (titleElement.getText().equals(""))
{
Flag = true;
// bookElement.remove(titleElement);
}
else
{
Flag = false;
break;
}
}
if (Flag)
{

//获得其父节点然后删除节点
bookElement.getParent().remove(bookElement);
}
}
OutputFormat opf=OutputFormat.createPrettyPrint();
XMLWriter xmr = new XMLWriter(new FileWriter(new File(file)),opf);
xmr.write(doc);
xmr.close();

}
}