如果您正在使用的XPath,你需要採取的命名空間考慮在內。
使用給XPathQuery樣品,可以給它:
String xpath = "//w:fldChar[./w:ffData/w:checkBox]";
(或變型,這取決於要選擇這三個節點中的)
的另一種方法是遍歷文檔,爲此,有TraversalUtils。
這兩種方法都在docx4j的Getting Started文檔中進行了說明。
如上所述,如果您修改了對象,則不能依賴Sun/Oracle JAXB XPath。
因此,手動遍歷通常會更好。
下面是如何做到這一點的例子。
package org.docx4j.samples;
import java.util.ArrayList;
import java.util.List;
import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.TraversalUtil.CallbackImpl;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.FldChar;
public class TraverseFind {
/**
* Example of how to find an object in document.xml
* via traversal (as opposed to XPath)
*
*/
public static void main(String[] args) throws Exception {
String inputfilepath = System.getProperty("user.dir") + "/checkbox.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
Finder finder = new Finder(FldChar.class);
new TraversalUtil(documentPart.getContent(), finder);
System.out.println("got " + finder.results.size() + " of type " + finder.typeToFind.getName());
for (Object o : finder.results) {
Object o2 = XmlUtils.unwrap(o);
// this is ok, provided the results of the Callback
// won't be marshalled
if (o2 instanceof org.docx4j.wml.Text) {
org.docx4j.wml.Text txt = (org.docx4j.wml.Text)o2;
System.out.println(txt.getValue());
} else {
System.out.println(XmlUtils.marshaltoString(o, true, true));
}
}
}
public static class Finder extends CallbackImpl {
protected Class<?> typeToFind;
protected Finder(Class<?> typeToFind) {
this.typeToFind = typeToFind;
}
public List<Object> results = new ArrayList<Object>();
@Override
public List<Object> apply(Object o) {
// Adapt as required
if (o.getClass().equals(typeToFind)) {
results.add(o);
}
return null;
}
}
}
我所做的這些例子的方式,他們都讓你的org.docx4j.wml.FldChar對象。
從那裏,你會發現裏面getFfData()你CTFFCheckBox。getNameOrEnabledOrCalcOnExit()
如果你想要的是複選框,然後就可以適應任何例子只是獲取。這會更簡單。
JasonPlutext,是否有任何解決方案,在** docx4j **複選框中設置值? – dimson
您應該發佈一個新問題,列出您遇到的問題。在Word文檔中有幾種類型的複選框,所以一些XML可以幫助你清楚你的問題。 – JasonPlutext
男人,在這裏我的新[問題](http://stackoverflow.com/questions/29540560/set-unset-checkbox-value-with-docx4j-in-ms-word-document)。謝謝! – dimson