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
精彩评论