2 回答
TA贡献1801条经验 获得超8个赞
首先,指定要删除的项目(在 XPath 返回的对象列表中)。
Object deleteMe = list.get(1);
使用代码:
Object parent = getParent(deleteMe);
if (parent instanceof ContentAccessor) {
boolean result = ((ContentAccessor)parent).getContent().remove(deleteMe);
System.out.println("Deleted? " + result);
} else {
System.out.println("TODO: get content list from " + parent.getClass().getName());
}
用一个小帮手方法:
private Object getParent(Object o) {
return ((Child)XmlUtils.unwrap(o)).getParent();
}
TA贡献1801条经验 获得超16个赞
我使用此代码作为基础。
一个有效的解决方案:
public class RemoveLastTable {
public static void main(String[] args) throws Docx4JException {
File doc = new File("d:\\tmp\\tables.docx");
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(doc);
removeLastTable(pkg, "d:\\tmp\\tables_updated.docx");
}
public static void removeLastTable(WordprocessingMLPackage wordMLPackage, String outFile) throws Docx4JException {
Body body = wordMLPackage.getMainDocumentPart().getContents().getBody();
List<Object> tables = getAllElementFromObject(body, Tbl.class);
int indexTableToRemove = tables.size() - 1;
Tbl tableToRemove = (Tbl) tables.get(indexTableToRemove);
body.getContent().remove(tableToRemove.getParent());
wordMLPackage.save(new File(outFile));
}
private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<>();
if (obj instanceof JAXBElement) {
obj = ((JAXBElement<?>) obj).getValue();
}
if (obj.getClass().equals(toSearch)) {
result.add(obj);
}
if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
}
然而更新文档的保存并不完美,我的Word 2016(Office 365)无法读取结果,只有在进行恢复之后。
添加回答
举报