DOCX4J XML how to get the “value” of a JAXBNodes

試著忘記壹切 提交于 2019-12-12 03:48:58

问题


I want to bind some XML variable in a docx file (my var are in that pattern $varname$). So I use a function which return a List<Object> with the result of my search over the document.

String xpath = "//w:r[w:t[starts-with(text(), '$')]]";
List<Object> list = this.getDocumentPart().getJAXBNodesViaXPath(xpath, false);
if(!list.isEmpty()){
    for(int i = 0; i < list.size(); ++i){
            System.out.println(list.get(i).getClass());
    }
}

The result of the print is:

class org.docx4j.wml.R
class org.docx4j.wml.R
class org.docx4j.wml.R

But now I want to get the "value" ie $varname$ to compare it with a map (the key is the name of each variable) ?


回答1:


Your XML is probably of the form:

<w:r>
    <w:t>$varname$</w:t>
</w:r>

But not necessarily. The could also have other content, so its content model is a list.

If you just want to replace $varname$ with some other plain text, then you'd be better using:

String xpath = "//w:t[starts-with(text(), '$')]";

since that will return the text objects; you'd then get their current value, then set it to something else.

The way you currently have it, you need to get the R's content list (start by casting the object to R), and inspect each item to see whether it is a w:t containing your $varname$.




回答2:


I find solution:

if(!list.isEmpty()){
    List<Object> listObjNode;
    for(int i = 0; i < list.size(); ++i){
        List<Object> r = ((R)list.get(i)).getContent();
        for(int j = 0; j < r.size(); ++j){
            javax.xml.bind.JAXBElement jaxb = (javax.xml.bind.JAXBElement)r.get(j);
            org.docx4j.wml.Text t = (org.docx4j.wml.Text)jaxb.getValue();
            System.out.println(t);
        }
    }
}


来源:https://stackoverflow.com/questions/43938012/docx4j-xml-how-to-get-the-value-of-a-jaxbnodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!