开发者

C# XML - Copy an attribute to a child element

开发者 https://www.devze.com 2023-01-21 16:19 出处:网络
For example I have an XML structure as follws: <element1> <element 2 name = \"Blah\" value = \"Something\">

For example I have an XML structure as follws:

<element1>
  <element 2 name = "Blah" value = "Something">
    <element 3 name = "Blah" type = "Something">
    <el开发者_JAVA技巧ement 3 name = "Woo" type = "Wibble">
      <element 4 name = "Hello">
      <element 4 name = "Goodbye">
      </element4>
    </element3>
  <element2>
</element1>

Rough structure guide only. No how would I in C# write an app that copies the value attribute in element 2 and places it in each instance of element 3, but only if it has an element 4 child?

For the commenter who asked for an example:

I wish to loop through the XML document and for each instance of element3 that contains an element4 child, I wish to copy the 'value' attribute in the element2 parent of that element3 and add it to the list of attributes in that element 3. If that makes sense :\


Well, I would:

  • Load the XML into an XDocument
  • Find <element2> using doc.Descendants("element2").First() or doc.Root.Element("element2")
  • Find the attribute value you'll want to copy, e.g. with string value = (string) element.Attribute("value");
  • Iterate over all all <element3> elements using doc.Root.Elements("element3")
  • Test each <element3> for children with element.Element("element4") != null
  • Call element.SetAttributeValue("value", value") on any appropriate elements.
0

精彩评论

暂无评论...
验证码 换一张
取 消