Search code examples
docx4j

Delete CustomXml files -docx4j


How to delete custom XML files with its property and relationship files?, I've used clear() method. But it's not working. Help me out.

wordMLPackage.getCustomXmlDataStorageParts().clear();

Solution

  • https://github.com/plutext/docx4j/blob/master/docx4j-core/src/main/java/org/docx4j/Docx4J.java#L643 shows you how to do this. To remove them all, it would be:

    protected static void removeDefinedCustomXmlParts(WordprocessingMLPackage wmlPackage) {
    List<PartName> partsToRemove = new ArrayList<PartName>();
    RelationshipsPart relationshipsPart = wmlPackage.getMainDocumentPart().getRelationshipsPart();
    List<Relationship> relationshipsList = ((relationshipsPart != null) && 
                                            (relationshipsPart.getRelationships() != null) ?
                                            relationshipsPart.getRelationships().getRelationship() : null);
    Part part = null;
        if (relationshipsList != null) {
            for (Relationship relationship : relationshipsList) {
                if (Namespaces.CUSTOM_XML_DATA_STORAGE.equals(relationship.getType())) {
                    part = relationshipsPart.getPart(relationship);
                    partsToRemove.add(part.getPartName());
                }
            }
        }
        if (!partsToRemove.isEmpty()) {
            for (int i=0; i<partsToRemove.size(); i++) {
                relationshipsPart.removePart(partsToRemove.get(i));
            }
        }
    }