我有一大堆XML文件,具有以下结构:
someContent someType someContent someType ... ... someContent someType
我需要将每个"Content"节点名称更改为StuffxContent; 基本上将父节点名称添加到内容节点的名称.
我打算用这个XMLDocument
课程找出一种方法,但我想我会问是否有更好的方法来做到这一点.
(1.)[XmlElement/XmlNode] .Name属性是只读的.
(2.)问题中使用的XML结构是粗略的,可以改进.
(3.)无论如何,这是给定问题的代码解决方案:
String sampleXml = ""+ " "; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(sampleXml); XmlNodeList stuffNodeList = xmlDoc.SelectNodes("//*[starts-with(name(), 'Stuff')]"); foreach (XmlNode stuffNode in stuffNodeList) { // get existing 'Content' node XmlNode contentNode = stuffNode.SelectSingleNode("Content"); // create new (renamed) Content node XmlNode newNode = xmlDoc.CreateElement(contentNode.Name + stuffNode.Name); // [if needed] copy existing Content children //newNode.InnerXml = stuffNode.InnerXml; // replace existing Content node with newly renamed Content node stuffNode.InsertBefore(newNode, contentNode); stuffNode.RemoveChild(contentNode); } //xmlDoc.Save"+ " "+ "someContent "+ "someType "+ ""+ " "+ "someContent "+ "someType "+ ""+ " "+ "someContent "+ "someType "+ "
PS:我来这里寻找一种更好的重命名节点/元素的方法; 我还在寻找.