【发布时间】:2015-03-17 13:21:27
【问题描述】:
我正在使用 docx4j 来处理 Microsoft Word 模板。我想知道如何删除或隐藏模板中的 P 元素。我能够遍历代码以获取特定的 P 元素,现在我需要知道如何删除或隐藏该 P 元素。任何人都可以帮忙吗?我使用以下代码获取所有 P 元素:
private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private void replaceTextValue_P(WordprocessingMLPackage template ) throws Exception{
List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), P.class);
// List<Object> pCon = new ArrayList<Object>();
for (Object text : texts) {
P textElement = (P) text;
template.getMainDocumentPart().getContent().remove(textElement); // DOES NOT WORK!
writeDocxToStream(template, "C:\\Temp\\Target.docx");
}
}
private void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException {
File f = new File(target);
template.save(f);
}
【问题讨论】: