更改XML根元素名称

9

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

<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>

我想要将XML标签<ItemMasterList>更改为<Masterlist>,我该怎么做?


1
你应该发布你正在使用的一小部分代码,因为有多种方法可以做到这一点。 - Robert Harvey
+1 for the question. 我本来打算赌一大笔钱这里不会有这样的问题。这是非常不寻常的情况。 - antanta
5个回答

14

1
修改后包含一个示例。 - Will A
1
对于更一般的情况,您可能需要担心根元素上的属性,对吧?foreach (XmlAttribute attNode in doc.DocumentElement.Attributes) { newRoot.Attributes.Append((XmlAttribute)docNew.ImportNode(attNode, true)); } - Ben

10

我知道我有点晚了,但是必须回答一下,因为似乎没有人知道这个。

XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");    
doc.Root.Name = "MasterList";

它返回以下内容:

<MasterList>
  <ItemMaster>
    <fpartno>xxx</fpartno>
    <frev>000</frev>
    <fac>Default</fac>
  </ItemMaster>
</MasterList>

更简单,只是重命名,其他保持不变。 - Horia

7
你可以使用 LINQ to XML 解析XML字符串,创建一个新根元素,并将原根元素的子元素和属性添加到新根元素中:
XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>");

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

0
如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;

0

使用XmlDocument的方式,您可以按照以下步骤执行此操作(并保持树形结构完整):

XmlDocument oldDoc = new XmlDocument();
oldDoc.LoadXml("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
XmlNode node = oldDoc.SelectSingleNode("ItemMasterList");

XmlDocument newDoc = new XmlDocument();
XmlElement ele = newDoc.CreateElement("MasterList");
ele.InnerXml = node.InnerXml;

如果您现在使用ele.OuterXml,它将返回:(如果您只需要字符串,否则请使用XmlDocument.AppendChild(ele),然后您将能够更多地使用XmlDocument对象)
<MasterList>
  <ItemMaster>
     <fpartno>xxx</fpartno>
     <frev>000</frev>
     <fac>Default</fac>
  </ItemMaster>
</MasterList>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接