使用C#更改XML文件中的节点名称 [英] Change the node names in an XML file using C#

查看:684
本文介绍了使用C#更改XML文件中的节点名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a huge bunch of XML files with the following structure:

<Stuff1>
  <Content>someContent</name>
  <type>someType</type>
</Stuff1>
<Stuff2>
  <Content>someContent</name>
  <type>someType</type>
</Stuff2>
<Stuff3>
  <Content>someContent</name>
  <type>someType</type>
</Stuff3>
...
...

我需要更改每个StuffxContent的 Content节点名称;

I need to change the each of the "Content" node names to StuffxContent; basically prepend the parent node name to the content node's name.

我计划使用 XMLDocument 类并找出一种方法,但是想过我会问是否有更好的方法可以做到这一点。

I planned to use the XMLDocument class and figure out a way, but thought I would ask if there were any better ways to do this.

推荐答案

您提供的XML显示

而不是拥有

<stuff1>
   <content/>
</stuff1>

您应该拥有:/

<stuff id="1">
    <content/>
</stuff>

现在您将能够使用Xpath遍历文档(即// stuff [id =' 1'] / content /)不应使用节点名称来建立标识,而应使用属性。

Now you would be able to traverse the document using Xpath (ie, //stuff[id='1']/content/) The names of nodes should not be used to establish identity, you use attributes for that.

要做的是,将XML加载到一个xml文档,然后简单地遍历子节点的第一级重命名它们。

To do what you asked, load the XML into an xml document, and simply iterate through the first level of child nodes renaming them.

伪代码:

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

YourDoc.Save();

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

However, I'd strongly recommend you actually fix the XML so that it is useful, instead of wreck it further.

这篇关于使用C#更改XML文件中的节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆