Wrap XmlNode with tags - C #

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 #).

+3
source share
3 answers

you can try something like this.

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;
XmlNode parent = node.ParentNode;
XmlElement xElement = xDoc.CreateElement("p");
parent.RemoveChild(node);
xElement.AppendChild(node);
parent.AppendChild(xElement);
+1
source

The above β€œbest answer” works if you don't care that the new β€œp” node ends 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);
+2
source

You should use CreateNode (XmlNodeType.Element, "p", "") XmlDocument.

Then add the old node to the new one using the AppendChild method

0
source

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


All Articles