我正在向docx添加一些自定义
XML,以便在我正在编写的应用程序中跟踪它.
我通过ZIP库打开Word文档,并通过官方Open XML SDK路由手动完成它.两者都有相同的结果,我的XML被插入到文档中的customXml文件夹中.对于这两种方法,Word中的文档打开正常,并且XML存在.
但是,当我将文档保存为MyDoc2.docx时,例如我的所有XML都消失了.
我究竟做错了什么?
Microsoft链接我一直关注:
http://msdn.microsoft.com/en-us/library/bb608597.aspx
http://msdn.microsoft.com/en-us/library/bb608612.aspx
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); } } }
谢谢,
约翰
解决方法
好的,所以我设法在openxmldeveloper.org上找到了以下文章
Using Custom XML Part as DataStore,并删除了不必要的代码,以便它插入并保留自定义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; } } }