将根节点添加到XML文档 [英] Add a root node to an XML Document

查看:80
本文介绍了将根节点添加到XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个Xml文档,

Hi,
I have a Xml document as,

'<?xml version="1.0" encoding="utf-8"?><root>some text here<pre lang="text"></pre><\root>'


我希望将XML放置在新标记中,如下所示,


I want my XML to be place inside a new tag as follows,

<data>

<?xml version="1.0" encoding="utf-8"?><root>some text here<pre lang="text"></pre><\root>

</data>


完美的解决方案是什么.

在此先感谢.


What would be the perfect solution for this.

Thanks in Advance.

推荐答案

您可以使用CDATA.

You can use CDATA.

<data>
<![CDATA[
<?xml version="1.0" encoding="utf-8"?><root>some text here<pre lang="text">


]]>


]]>


public static void Main()
 {
   XmlDocument docA = new XmlDocument();
   XmlDocument docB = new XmlDocument();

   docA.LoadXml("<?xml version=""1.0"" encoding=""utf-8""?><root>some text here<pre lang=""text""></pre></root>");
   docB.loadXml("<?xml version=""1.0"" encoding=""utf-8""?><data></data>");

    System.IO.StringWriter sw;
    sw = new System.IO.StringWriter();
    docA.Save(sw);
   //Create a CData section.
   XmlCDataSection CData;
   CData = docB.CreateCDataSection(sw.ToString());

   //Add the new node to the document.
   XmlElement root = docB.DocumentElement;
   root.AppendChild(CData);

   docB.save("C:\\result.xml");

 }


尝试以下代码

Try following code

XmlDocument origXml = new XmlDocument();
origXml.Load("YourXml.Xml");

XmlDocument newXml = new XmlDocument();
newXml.LoadXml("<data></data>");


XmlNode rootNode= newXml.ImportNode(origXml.DocumentElement, true);

newXml.DocumentElement.AppendChild(rootNode);



希望能有所帮助.如果是这样,请将其标记为答案/赞.
-Milind



Hope that helps. If it does, mark it as answer/upvote.
-Milind


这篇关于将根节点添加到XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆