使用C#更改XML文件中的节点名称

sun*_*eep 14 c# xml

我有一大堆XML文件,具有以下结构:

<Stuff1>
  <Content>someContent</name>
  <type>someType</type>
</Stuff1>
<Stuff2>
  <Content>someContent</name>
  <type>someType</type>
</Stuff2>
<Stuff3>
  <Content>someContent</name>
  <type>someType</type>
</Stuff3>
...
...
Run Code Online (Sandbox Code Playgroud)

我需要将每个"Content"节点名称更改为StuffxContent; 基本上将父节点名称添加到内容节点的名称.

我打算用这个XMLDocument课程找出一种方法,但我想我会问是否有更好的方法来做到这一点.

Oma*_*mar 55

(1.)[XmlElement/XmlNode] .Name属性是只读的.

(2.)问题中使用的XML结构是粗略的,可以改进.

(3.)无论如何,这是给定问题的代码解决方案:

String sampleXml =
  "<doc>"+
    "<Stuff1>"+
      "<Content>someContent</Content>"+
      "<type>someType</type>"+
    "</Stuff1>"+
    "<Stuff2>"+
      "<Content>someContent</Content>"+
      "<type>someType</type>"+
    "</Stuff2>"+
    "<Stuff3>"+
      "<Content>someContent</Content>"+
      "<type>someType</type>"+
    "</Stuff3>"+
  "</doc>";

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
Run Code Online (Sandbox Code Playgroud)

PS:我来这里寻找一种更好的重命名节点/元素的方法; 我还在寻找.

  • 令人遗憾的是,有51名代表的人比拥有31k代表的人更了解这一点.为你+1,即使它是一个比我希望的稍微复杂的解决方案. (4认同)
  • 它不会影响提问者的例子,但为了完整性,你的例程不应该仅仅复制到InnerXml,它还应该复制任何属性:for(int i = contentNode.Attributes.Count - 1; i> = 0; i - ){ newNode.Attributes.Prepend((XmlAttribute)contentNode.RemoveAttributeAt(I)); } (3认同)

Fly*_*wat -33

您提供的 XML 表明有人完全没有理解 XML 的要点。

而不是有

<stuff1>
   <content/>
</stuff1>
Run Code Online (Sandbox Code Playgroud)

你应该有:/

<stuff id="1">
    <content/>
</stuff>
Run Code Online (Sandbox Code Playgroud)

现在您将能够使用 Xpath 遍历文档(即 //stuff[id='1']/content/) 节点的名称不应该用于建立身份,您可以使用属性来建立身份。

要执行您所要求的操作,请将 XML 加载到 xml 文档中,然后简单地迭代第一级子节点并重命名它们。

伪代码:

foreach (XmlNode n in YourDoc.ChildNodes)
{        
    n.ChildNode[0].Name = n.Name + n.ChildNode[0].Name;
}

YourDoc.Save();
Run Code Online (Sandbox Code Playgroud)

不过,我强烈建议您实际修复 XML,使其有用,而不是进一步破坏它。

  • 我无法理解为什么这被标记为正确,因为正如下面 DeepBlue 所说,Name 属性是只读的。令人着迷的是它获得了 11 票赞成...... (6认同)