Why does my custom XML not carry over to a new version of a DOCX file when Word saves it?

荒凉一梦 提交于 2019-12-10 03:52:08

问题


I'm adding in some custom XML to a docx for tracking it inside an application I'm writing.

I've manually done it via opening the Word Document via a ZIP library, and via the official Open XML SDK route. Both have the same outcome of my XML being inserted into customXml folder in the document. The document opens fine in Word for both of these methods, and the XML is present.

BUT when I then save the document as MyDoc2.docx for example all my XML disappears.

What am I doing wrong?

Microsoft links I've been following:

http://msdn.microsoft.com/en-us/library/bb608597.aspx
http://msdn.microsoft.com/en-us/library/bb608612.aspx

And the code I've taken from the Open XML SDK 2.0:

public static void AddNewPart(string document, string fileName)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        MainDocumentPart mainPart = wordDoc.MainDocumentPart;

        CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);

        using (FileStream stream = new FileStream(fileName, FileMode.Open))
        {
            myXmlPart.FeedData(stream);
        }
    }
}

Thanks, John


回答1:


Ok,so I managed to find the following article Using Custom XML Part as DataStore on openxmldeveloper.org, and have stripped out the unnecessary code so that it inserts and retains custom XML:

static void Main(string[] args)
{
    using (WordprocessingDocument doc = WordprocessingDocument.Open("Test.docx", true, new OpenSettings()))
    {
        int customXmlPartsCount = doc.MainDocumentPart.GetPartsCountOfType<CustomXmlPart>();

        if (customXmlPartsCount == 0)
        {
            CustomXmlPart customXmlPersonDataSourcePart = doc.MainDocumentPart.AddNewPart<CustomXmlPart>("application/xml", null);
            using (FileStream stream = new FileStream("Test.xml", FileMode.Open))
            {
                customXmlPersonDataSourcePart.FeedData(stream);
            }


            CustomXmlPropertiesPart customXmlPersonPropertiesDataSourcePart = customXmlPersonDataSourcePart
                                                                              .AddNewPart<CustomXmlPropertiesPart>("Rd3c4172d526e4b2384ade4b889302c76");

            Ds.DataStoreItem dataStoreItem1 = new Ds.DataStoreItem() { ItemId = "{88e81a45-98c0-4d79-952a-e8203ce59aac}" };
            customXmlPersonPropertiesDataSourcePart.DataStoreItem = dataStoreItem1;
        }
    }
}

So all the examples from Microsoft work as long as you don't modify the file. The problem appears to be because we don't setup the relationship with the Main Document.



来源:https://stackoverflow.com/questions/6341845/why-does-my-custom-xml-not-carry-over-to-a-new-version-of-a-docx-file-when-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!