这就是我设法替换页脚上的键持有者的方法(在 Java 中,没有 XML)。我缺少的是:
JaxbXmlPart part = (JaxbXmlPart) relationshipPart.getPart(r);
来自JasonPlutext提到的源代码MailMerger.java,在第 410 行中说明。所以谢谢JasonPlutext!
public static void replaceElementFromFooter(WordprocessingMLPackage template, String nameplace, String placeholder, String newValue) throws Docx4JException {
List<Object> result = new ArrayList<Object>();
RelationshipsPart relationshipPart = template.getMainDocumentPart().getRelationshipsPart();
List<Relationship> relationships = relationshipPart.getRelationships().getRelationship()
for (Relationship r : relationships) {
if (r.getType().equals(nameplace)) {
JaxbXmlPart part = (JaxbXmlPart) relationshipPart.getPart(r);
List<Object> texts = getAllElementsFromObject(part.getContents(), Text.class);
replaceTextElement(texts, placeholder, newValue);
}
}
return result;
}
private static List<Object> getAllElementsFromObject(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 static void replaceTextElement(List<Object> texts, String placeholder, String newValue) {
for (Object element : texts) {
Text textElement = (Text) element;
if (textElement.getValue().contains(placeholder)) {
String replacedValue = textElement.getValue().replaceAll(placeholder, newValue);
textElement.setValue(replacedValue);
}
}
}