更改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的情况,下面的解决方案将会解决:

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