Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap XmlNode with tags - C#

Tags:

c#

.net

xml

I have the following xml:

<span>sometext</span>

and I want to wrap this XmlNode with another tag:

<p><span>sometext</span></p>

How can i achieve this. For parsing i use XmlDocument (C#).

like image 525
kjv Avatar asked May 31 '26 00:05

kjv


1 Answers

The above "best answer" works if you don't care that the new "p" node ends up at the end of the parent. To replace it where it is, use:

string xml = "<span>sometext</span>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
// If you have XmlNode already, you can start from this point
XmlNode node = xDoc.DocumentElement;
XmlElement clone = node.Clone();
XmlNode parent = node.ParentNode;

XmlElement xElement = xDoc.CreateElement("p");
xElement.AppendChild(clone);
parent.ReplaceChild(xElement, node);
like image 137
Mestaris Avatar answered Jun 02 '26 16:06

Mestaris