Yesterday I came across the following situation:

1) Load a XML File.

2) Parse the elements that match certain criteria.

3) Set the elements value to a new data

The only problem in the above situation was that I was dealing with CDATA inside the element.

Sample XML:

<employees>
    <employee>
        <description>
            <![CDATA[Lorem Ipsum]]>
        </description>
    </employee>
    ....
</employees>

The C# fragment that will allow you to manipulate the above elment is:

public void ParseEmployeeDescription(XDocument document)
{
	var result = from e in document.Descendants("description")
				 select e;
	foreach (var element in result)
	{
		if(/*Some condition matches*/)
		{
			var temp = element.Value;

			temp += "modified";
			//Replace with new data in the CDATA tag
			((XCData)element.FirstNode).Value = pTagData;

		}

	}
	document.Save("new_employees.xml");
}

Hopefully this helps someone :)

Post to Twitter