OpenXML替换Word文档中特定的customxml部分

问题描述:

我正在使用OpenXML SDK ver 2操纵某些Word文档.这些文档当前具有自定义的xml部件,我想做的是专门替换这些部件的xml.

I am using OpenXML SDK ver 2 to manipulate some word documents. The documents currently have custom xml parts and what I want to do is replace the xml for the parts specifically.

我知道我可以做这样的事情来访问文档的customxml部分:

I know I can do something like this to access the customxml parts of a document:

Dim mainStream As New MemoryStream()
Dim buffer As Byte() = File.ReadAllBytes(Server.MapPath("myfile.docx"))
mainStream.Write(buffer, 0, buffer.Length)

Try
  Using mainDocument As WordprocessingDocument = WordprocessingDocument.Open(mainStream, True)

  MainDocumentPart mainPart = mainDocument.MainDocumentPart;
  'collection of custom xml parts
   Dim parts = mainPart.CustomXmlParts
   For Each part As CustomXmlPart In parts
     'how do I replace the xml here??
   Next

但是正如您所看到的,我不确定如何替换零件的XML.我的文档有两个XML部分,分别称为item1.xml和item2.xml.我想替换那些部分中的XML.我知道我可以使用.DeleteParts()删除现有的xml部件,也可以使用AddCustomXmlPart()创建新的部件,但是我不想这样做.我只想替换现有部分的XML.

But as you can see I'm not sure how to replace the XML of the part. My document has two XML parts called item1.xml and item2.xml. I want to replace the XML in those parts. I know I can use .DeleteParts() to remove the existing xml parts and I can use AddCustomXmlPart() to create new parts but I don't want to do that. I simply want to replace the XML for the existing parts.

有人可以建议我怎么做吗?任何建议表示赞赏.

Could anyone suggest how I could do this? Any advice is appreciated.

谢谢.

编辑,哎呀,忘记了代码标签

Edit oops forgot the code tags

使用CustomXmlPart实例的FeedData()方法替换 定制xml部分的XML. FeedData()方法首先被截断 零件流,然后将新数据写入零件流. 因此,您可以使用此方法替换现有自定义xml部分中的XML.

Use the FeedData() method of the CustomXmlPart instance to replace the XML of the custom xml part. The FeedData() method at first truncates the stream of the part, then writes the new data to the part stream. So, you could use this method to replace the XML in an existing custom xml part.

MainDocumentPart mainPart = mainDocument.MainDocumentPart;

Dim parts = mainPart.CustomXmlParts

For Each part As CustomXmlPart In parts

  Dim ms As New MemoryStream
  Dim xtw As New XmlTextWriter(ms, Encoding.UTF8)

  ' Create your xml.'

  xtw.WriteStartDocument() 
  xtw.WriteStartElement("bla")
  xtw.WriteEndElement()
  xtw.WriteEndDocument()
  xtw.Flush()

  ms.Seek(0, SeekOrigin.Begin)

  part.FeedData(ms) ' Replace old xml in part stream.'

  xtw.Close()    

Next