我有XML存储在字符串变量中:
<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>
Run Code Online (Sandbox Code Playgroud)
在这里,我想将XML标记更改<ItemMasterList>为<Masterlist>.我怎样才能做到这一点?
Wil*_*l A 11
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;
Run Code Online (Sandbox Code Playgroud)
我知道我有点晚了,但只是必须添加这个答案,因为似乎没有人知道这个.
XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
doc.Root.Name = "MasterList";
Run Code Online (Sandbox Code Playgroud)
返回以下内容:
<MasterList>
<ItemMaster>
<fpartno>xxx</fpartno>
<frev>000</frev>
<fac>Default</fac>
</ItemMaster>
</MasterList>
Run Code Online (Sandbox Code Playgroud)
您可以使用LINQ to XML来解析XML字符串,创建新根并将原始根的子元素和属性添加到新根:
XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>");
XDocument result = new XDocument(
new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes()));
Run Code Online (Sandbox Code Playgroud)