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>
usingdoc.Descendants("element2").First()
ordoc.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 usingdoc.Root.Elements("element3")
- Test each
<element3>
for children withelement.Element("element4") != null
- Call
element.SetAttributeValue("value", value")
on any appropriate elements.
精彩评论