how to search through unstructured XML?
I have something like this:
<group name="name1" ... >
<group name="name2" ... >
<image name="test1" ...>
<image name="test2" ...></image>
<开发者_如何学Python;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>
As you can see is not organized. Also is not fixed, neither node names nor the order. I don't know what nodes i'm goin to change. (besides group and image it probably has a lot more)
What i want is to clone the first node then search for specific attributes to change their values. Some of them have an attribute called "path" other have only other called "left".
do you think it could be easier convert xml into text?
Loading the XML onto a XmlDocument
(or XDocument
) will give you the power to use XPath queries, and you can find the attribute names quite easily, as shown in the example below.
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);
}
}
精彩评论