これは、フッターのキーホルダーを置き換える方法です(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);
}
}
}