Why is my custom XML not migrated to the new version of the DOCX file when Word saves it?

I am adding some kind of custom XML to docx to track it inside the application that I am writing.

I manually did this by opening a Word document through the ZIP library and through the official Open XML SDK route. Both have the same result as my XML inserted into the customXml folder in the document. The document opens perfectly in Word for both of these methods, and XML is present.

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

What am I doing wrong?

Microsoft links I'm following:

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

And the code I took 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

+6
source share
1 answer

So, I managed to find the following article Using a custom XML part as a DataStore on openxmldeveloper.org and cutting out unnecessary code so that it inserts and saves 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 until you modify the file. The problem is that we are not communicating with the main document.

+5
source

Source: https://habr.com/ru/post/890490/


All Articles