Csharp/C#教程:更改XML根元素名称分享


更改XML根元素名称

我有XML存储在字符串变量中:

xxx000Default 

在这里,我想将XML标签更改为 。 我怎样才能做到这一点?

System.Xml.XmlDocument以及相同名称空间中的关联类在这里对您来说非常宝贵。

 XmlDocument doc = new XmlDocument(); doc.LoadXml(yourString); XmlDocument docNew = new XmlDocument(); XmlElement newRoot = docNew.CreateElement("MasterList"); docNew.AppendChild(newRoot); newRoot.InnerXml = doc.DocumentElement.InnerXml; String xml = docNew.OuterXml; 

您可以使用LINQ to XML来解析XML字符串,创建新根并将原始根的子元素和属性添加到新根:

 XDocument doc = XDocument.Parse("..."); XDocument result = new XDocument( new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes())); 

我知道我有点晚了,但只是必须添加这个答案,因为似乎没有人知道这个。

 XDocument doc = XDocument.Parse("xxx000Default"); doc.Root.Name = "MasterList"; 

返回以下内容:

   xxx 000 Default   

使用XmlDocument方式,您可以执行以下操作(并保持树完整):

 XmlDocument oldDoc = new XmlDocument(); oldDoc.LoadXml("xxx000Default"); XmlNode node = oldDoc.SelectSingleNode("ItemMasterList"); XmlDocument newDoc = new XmlDocument(); XmlElement ele = newDoc.CreateElement("MasterList"); ele.InnerXml = node.InnerXml; 

如果你现在使用ele.OuterXml将返回:(你只需要字符串,否则使用XmlDocument.AppendChild(ele)你将能够更多地使用XmlDocument对象)

   xxx 000 Default   

正如Will A所指出的那样,我们可以这样做,但是对于InnerXml等于OuterXml的情况,下面的解决方案将会解决:

上述就是C#学习教程:更改XML根元素名称分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 // Create a new Xml doc object with root node as "NewRootNode" and // copy the inner content from old doc object using the LastChild. XmlDocument docNew = new XmlDocument(); XmlElement newRoot = docNew.CreateElement("NewRootNode"); docNew.AppendChild(newRoot); // The below line solves the InnerXml equals the OuterXml Problem newRoot.InnerXml = oldDoc.LastChild.InnerXml; string xmlText = docNew.OuterXml; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1009995.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐