문제

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()];
            }
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top