Insert an XML string into an openXML document

I am trying to replace a text element placeholder with an image in openXML docx.

I found a tutorial here that seems to do what I need, but I don’t quite understand what it does to insert an image.

Basically, I have an XML image template stored in a string. I can save the image to the media folder and paste the image ID into the XML string:

string imageNode 
         = _xml.Replace("##imageId##", documentMainPart.GetIdOfPart(newImage));

so now I have the correct XML as a string that I need to insert into the document.

I can find the placeholder text node that I want to replace with a new XML image

var placeholder = documentMainPart.Document.Body
               .Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>()
               .Where(t => t.Text.Contains("##imagePlaceholder##")).First();

But here I am stuck. I do not see how to make a replacement / insert that will accept an XML string. I managed to get my XML output as text in a document, but I decided to somehow convert it to an XML element.

+3
source share
2 answers

If you are asking how to import XML that displays an image, this should not be a big problem.

How you store the image, I'm not sure though, but I think you will have to import it with the correct name somewhere inside .docx, but I assume that you know this by reading the message.

Replacing placeholder with xml image thingy is easy

var parent = placeholder.Parent;
parent.ReplaceChild(imageXML, placeholder);

thingy , , . , run, , , .

, XML , , . , Drawing/Inline/Graphic root.

+1

xml node, XML-, XmlDocument.CreateFragment:

XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = imageXML;
placeholder.Parent.ReplaceChild(docFrag,placeholder);
+1

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


All Articles