简体   繁体   中英

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

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) ?

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 aw:t containing your $varname$.

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM