我有这样的东西:
<group name="name1" ... >
<group name="name2" ... >
<image name="test1" ...>
<image name="test2" ...></image>
<group name="test98"...>
<image name="test67" ...>
<group name="test987"...>
<text name="asddd"...></text>
</group>
</image>
</group>
<group name="name22" ... >
<image name="test3" ...></image>
</group>
</image>
<image name="test4" ...>
<text name="asddd"...></text>
</image>
</group>
</group>
如你所见,是没有组织的。也不是固定的,既不是节点名也不是顺序。我不知道我要改变哪些节点。(除了组和图像,它可能有更多)
我想要的是克隆第一个节点,然后搜索特定的属性来改变它们的值。其中一些有一个名为"path"的属性,另一些只有一个名为"left"的属性。
你认为把XML转换成文本会更容易吗?
将XML加载到XmlDocument
(或XDocument
)将使您能够使用XPath查询,并且您可以很容易地找到属性名,如下面的示例所示。
public class StackOverflow_7276178
{
const string XML = @"<group name='name1' >
<group name='name2' >
<image name='test1' >
<image name='test2' ></image>
<group name='test98'>
<image name='test67' >
<group name='test987'>
<text name='asddd' path='myPath'></text>
</group>
</image>
</group>
<group name='name22' >
<image name='test3' left='myLeft'></image>
</group>
</image>
<image name='test4'>
<text name='asddd'></text>
</image>
</group>
</group>";
public static void Test()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(XML);
foreach (XmlAttribute pathAttr in doc.SelectNodes("//@path"))
{
pathAttr.Value = pathAttr.Value + "_modified";
}
foreach (XmlAttribute leftAttr in doc.SelectNodes("//@left"))
{
leftAttr.Value = leftAttr.Value + "_modified";
}
Console.WriteLine(doc.OuterXml);
}
}