开发者

Wrap XmlNode with tags - C#

开发者 https://www.devze.com 2022-12-20 05:44 出处:网络
I have the following xml: <span>sometext</spa开发者_运维知识库n> and I want to wrap this XmlNode with another tag:

I have the following xml:

<span>sometext</spa开发者_运维知识库n>

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


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);


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);


You must use the CreateNode(XmlNodeType.Element, "p", "") of XmlDocument.

Then append the old node to the new one with the AppendChild method

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号