gpt4 book ai didi

java - docx4j - 删除 wml P 元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:49 25 4
gpt4 key购买 nike

我正在使用 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);
}

最佳答案

如果你想删除一个P(即textElement instanceof P),你只需将它从包含列表中删除,即

template.getMainDocumentPart().getContent().remove(textElement )

但我认为你的意思是删除文本内容。

工作方式相同,即:

p.getContent().remove(textElement )

看着:

public void replaceElement(Object current, List insertions) {
int index = content.indexOf(current);

if (index > -1 ) {
content.addAll(index+1, insertions);
Object removed = content.remove(index);

// sanity check
if (!current.equals(removed)) {
log.error("removed wrong object?");
}
} else {
// Not found
log.error("Couldn't find replacement target.");
}
}

如果您传入的当前 Object 仅匹配包装在 JAXBElement 中的内容,则该方法将无法正常工作。它需要一个小的修复来解决这种情况。

关于java - docx4j - 删除 wml P 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com