I am using the OpenXML .NET Library to work on a WordprocessingML document. I need to replace/set the text for a <t>
element, but when I do it like this: Element.InnerXml = value
i get this error: System.InvalidOperationException: 'This OpenXmlLeafElement's InnerXml can only be set to null or to an empty string.'
. I looked into the documentation, but it seems incomplete and does not mention this error. This behaviour is unique to some of the leaf nodes (for now I only found it with Text
/<t>
), as I can set the parent InnerXml without an issue.
Currently I use a workaround where I replace the parent InnerXml, but seems very hacky to me (and will fail in some cases)
var Parent = Element.Parent ?? throw new InvalidOperationException("Leaf node without parent!");
int childIndex = Parent.ChildElements.Select((elem, i) => (elem, i)).First((e) => e.elem == Element).i;
Parent.InnerXml = Parent.InnerXml.Replace(">" + Element.InnerXml + "<", ">" + value + "<");
Element = Parent.ChildElements[childIndex];
I have also tried/considered:
- Similar workaround using the Element.OuterXml property in the replace (still not very nice and also adds weird namespace attributes that break the document)
- Cloning the child, editing the content and then replacing the child (doesn’t work, still cannot set the InnerXml)
- Removing the child and creating a new element (the code should work with any LeafElement type -> added complexity)
- InnerText is protected (even though in the docs imply it can be used to set text)
I might just be missing somethign in the docs, but I feel like there ought to be an easy way to set the text of a text element…