C# XML – Copy an attribute to a child element – Education Career Blog

For example I have an XML structure as follws:

<element1>
  <element 2 name = "Blah" value = "Something">
    <element 3 name = "Blah" type = "Something">
    <element 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.

Leave a Comment