fearofawhackplanet
fearofawhackplanet

Reputation: 53446

Insert an XML string into an openXML document

I'm trying to replace a text element placeholder with an image in an 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. I can store my image to media folder and insert 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 which I need to insert into the document.

I can find my placeholder text node which I want to replace with the new image 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. I've managed to get my XML output as text in the document, but I beed to somehow convert it into an XML element.

Upvotes: 3

Views: 3136

Answers (2)

RobinG
RobinG

Reputation: 196

To convert your string representation to an xml node belonging to the xml document, use XmlDocument.CreateFragment:

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

Upvotes: 1

Ing&#243; Vals
Ing&#243; Vals

Reputation: 4898

If you are asking how you import the XML that displays the image then it shouldn't be a big problem.

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.

Replacing the placeholder with the image xml thingy is easy

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. It should be Drawing/Inline/Graphic root I think.

Please comment If I'm misunderstanding your question

Upvotes: 1

Related Questions