docx4j-删除wml P元素 [英] docx4j - delete wml P element

查看:196
本文介绍了docx4j-删除wml P元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用docx4j处理Microsoft Word模板.我想知道如何在模板中删除或隐藏P元素.我能够遍历代码以获取特定的P元素,现在我需要知道如何删除或隐藏该P元素.有人可以帮忙吗?我使用以下代码获取所有P元素:

I'm using docx4j to work with a Microsoft Word template. I want to know how to either remove or hide a P element in the template. I'm able to traverse the code to get a specific P element, now I need to know how to remove or hide that P element. Can anyone help? I get all the P elements using the following code:

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),只需将其从包含列表中删除,即

If you want to remove a P (ie textElement instanceof P), you just remove it from the containing list, ie

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

但是我想你的意思是删除文本内容.

But I think you mean delete text content.

以相同的方式工作,即:

That works the same way, ie:

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 current仅匹配包装在JAXBElement中的内容,那么该方法将无效.需要解决此问题的小问题.

that method as it stands wouldn't work if the Object current you are passing in only matches something wrapped in JAXBElement. It needs a small fix to address that case.

这篇关于docx4j-删除wml P元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆