[英]Insert an XML string into an openXML document
I'm trying to replace a text element placeholder with an image in an openXML docx. 我正在尝试用openXML docx中的图像替换文本元素占位符。
I've found a tutorial here which seems to do what I need, but I'm not quite following what he does to insert the image. 我在这里找到了一个似乎可以做我需要的教程,但是我并没有完全遵循他插入图像所做的工作。
Basically, I have an XML 'image template' stored in a string. 基本上,我有一个XML'图像模板'存储在一个字符串中。 I can store my image to media folder and insert the image ID into the XML string: 我可以将我的图像存储到媒体文件夹并将图像ID插入XML字符串:
string imageNode
= _xml.Replace("##imageId##", documentMainPart.GetIdOfPart(newImage));
so now I have the correct XML as a string which I need to insert into the document. 所以现在我有正确的XML作为一个字符串,我需要插入到文档中。
I can find my placeholder text node which I want to replace with the new image XML 我可以找到我想用新图像XML替换的占位符文本节点
var placeholder = documentMainPart.Document.Body
.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>()
.Where(t => t.Text.Contains("##imagePlaceholder##")).First();
But this is where I get stuck. 但这是我被卡住的地方。 I can't see how to do a replace/insert which will take an XML string. 我看不到如何进行替换/插入将采用XML字符串。 I've managed to get my XML output as text in the document, but I beed to somehow convert it into an XML element. 我已经设法将我的XML输出作为文本中的文本,但我想以某种方式将其转换为XML元素。
If you are asking how you import the XML that displays the image then it shouldn't be a big problem. 如果您询问如何导入显示图像的XML,那么它应该不是一个大问题。
How you store the image I'm not sure though, but I guess you will have to import it with a proper name somewhere inside the .docx but I'm assuming you know this by reading your post. 你如何存储图像我不确定,但我想你必须在.docx内部的某个地方导入它,但我假设你通过阅读你的帖子知道这一点。
Replacing the placeholder with the image xml thingy is easy 用图像xml thingy替换占位符很容易
var parent = placeholder.Parent;
parent.ReplaceChild(imageXML, placeholder);
Here you are actually replacing the image thingy with the text tag but I can't be sure how that would work. 在这里,您实际上是用文本标签替换图像,但我不能确定它是如何工作的。 I know that a Image could be within a run tag wich I assume is the parent of your text tag. 我知道图像可以在运行标记内,我认为它是文本标记的父级。
Now if your XML you get form your command is correct you should be OK. 现在,如果您获得的XML形式是正确的,那么您应该没问题。 It should be Drawing/Inline/Graphic root I think. 它应该是Drawing / Inline / Graphic root我想。
Please comment If I'm misunderstanding your question 请评论如果我误解了你的问题
To convert your string representation to an xml node belonging to the xml document, use XmlDocument.CreateFragment: 要将字符串表示形式转换为属于xml文档的xml节点,请使用XmlDocument.CreateFragment:
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = imageXML;
placeholder.Parent.ReplaceChild(docFrag,placeholder);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.