Search code examples
javaxmldocx4j

How to add new CustomXmlDataStoragePropertiesPart if the docx already have some?


Actually I added custom xml for docx file which already don't have custom xml and if the docx already have customxml my code just overwrite the existing one(item1 and itemprops1). Say I have docx with customxml. In that custom xml folder there are already eight xmls (item1.xml, item2.xml........item4.xml and itemprops1.xml.........itemprops4.xml). Some how I managed to my elements in new xml (item5.xml) but it doesn't create itemprops5.xml for item5.xml instead it overwrite the itemprops1.xml.

Some of my code are give below for your reference:

CustomXmlDataStoragePart custom = new CustomXmlDataStoragePart();

PartName ps = custom.getPartName();
Parts pn = wordMLPackage.getParts();

    CustomXmlDataStoragePart customXmlDataStoragePart = null;

    if (pn.get(ps) == null) {

    customXmlDataStoragePart =injectCustomXmlDataStoragePart(documentPart, wordMLPackage.getParts());
    addProperties(customXmlDataStoragePart);

    } else {

            custom = injectCustomXmlDataStoragePart(documentPart, wordMLPackage.getParts());
            addProperties(custom);

            customXmlDataStoragePart = custom;
        }

Solution

  • Please see the sample ContentControlsAddCustomXmlDataStoragePart.java

    At line 84, it says:

    parent.addTargetPart(customXmlDataStoragePart, AddPartBehaviour.RENAME_IF_NAME_EXISTS);
    

    AddPartBehaviour.RENAME_IF_NAME_EXISTS ensures any existing part is not overwritten, by giving the part a new name.

    (Alternatively, you could use the part constructor which takes a PartName argument, to specify the part name you want.)

    Please try this sample to confirm it does what you want. Then you can try adapting the code.