I am converting codes in an XDocument from one format to another. My code looks like this:
if (translate.Count > 0)
{
foreach (XElement element in xml.Descendants())
{
if (translate.ContainsKey(element.Value.ToLower()))
element.Value = translate[element.Value.ToLower()];
}
}
The problem is, when I check the value of an XElement that looks like this:
<Element>
<InnerElement>
<Inner2Element>
<TargetValue>F-01751</TargetValue>
</Inner2Element>
</InnerElement>
</Element>
The value equals F-01751. If I then change it to a new value, my XML looks like this:
<Element>NewValue</Element>
Is there a way, using XElement, to parse through the XDocument one line at a time rather than recursively? Alternately, is there a way to check the value of only the element being examined, and not any of the child elements? I know I can convert this to an XmlDocument, and accomplish this, but that seems rather extreme. Does anyone have any other suggestions?
You should look for text child nodes (with NodeType = XmlNodeType.Text ) and replace those. These will be of type XText:
if (translate.Count > 0)
{
foreach (XText node in xml.Descendants().Nodes().OfType<XText>())
{
if (translate.ContainsKey(node.Value.ToLower()))
node.Value = translate[node.Value.ToLower()];
}
}