Reputation: 8599
I have following xml:
<div>foo 123 <span id=123>bar</span> baz</div>
And I would like to wrap 123 with a
element:
<div>foo <a>123</a> <span id=123>bar</span> baz</div>
What I tried?
1) I cannot make a replacement on InnerXml of div element like:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<div>foo 123 <span id='123'>bar</span> baz</div>");
var xmlElement = xmlDocument.DocumentElement;
xmlElement.InnerXml = xmlElement.InnerXml.Replace("123", "<a>123</a>");
It will result into invalid xml:
System.Xml.XmlException : '<', hexadecimal value 0x3C, is an invalid attribute character. Line 1, position 26.
2) Also it doesn't let me to replace InnerXml of 1st node inside div element like:
var childNode = xmlDocument.ChildNodes[0].ChildNodes[0];
childNode.InnerXml = childNode.InnerXml.Replace("123", "<a>123</a>");
Because:
System.InvalidOperationException : Cannot set the 'InnerXml' for the current node because it is either read-only or cannot have children.
3) I could possibly change 1st Text node to get rid of "123 ", insert new element with 123 after text node. and insert new text node after the element with 123 (with remaining white-space). However it doesn't let me to create a new instance of XmlText.
Upvotes: 0
Views: 2139
Reputation: 1302
This is not a perfect solution, but you can replace "123" text by Regex:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<div>foo 123 <span id='123'>bar</span> baz</div>");
var xmlElement = xmlDocument.DocumentElement;
xmlElement.InnerXml = Regex.Replace(xmlElement.InnerXml, "([^\"]123[^\"])", " <a>123</a>");
Upvotes: 1
Reputation: 37337
You can try this code. But remember that this code still needs some work to secure from exceptions:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<div>foo 123 <span id='123'>bar</span> baz</div>");
// get first child and the ID from second child
var firstChild = xmlDocument.FirstChild.FirstChild;
var id = firstChild.NextSibling.Attributes[0].Value;
// remove the ID from the text
firstChild.Value = firstChild.Value.Replace(id, "");
// create the node and set it's inner text to ID
var node = xmlDocument.CreateNode("element", "a", "");
node.InnerText = id;
// append created element to XML
xmlDocument.FirstChild.InsertAfter(node, firstChild);
Upvotes: 1