[英]C# XML - Copy an attribute to a child element
For example I have an XML structure as follws: 例如,我具有以下XML结构:
<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?
我不会用C#编写一个将value属性复制到元素2中并将其放置在元素3的每个实例中的应用程序,但是仅当它有一个元素4的孩子时才行吗?
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 :\\ 我希望遍历XML文档,对于包含element4子元素的element3的每个实例,我希望将“ value”属性复制到该element3的父元素中,并将其添加到该元素3的属性列表中。那讲得通 :\\
Well, I would: 好吧,我会:
XDocument
XDocument
<element2>
using doc.Descendants("element2").First()
or doc.Root.Element("element2")
doc.Descendants("element2").First()
或doc.Root.Element("element2")
查找<element2>
string value = (string) element.Attribute("value");
string value = (string) element.Attribute("value");
<element3>
elements using doc.Root.Elements("element3")
doc.Root.Elements("element3")
所有<element3>
元素 <element3>
for children with element.Element("element4") != null
element.Element("element4") != null
为孩子测试每个<element3>
element.Element("element4") != null
element.SetAttributeValue("value", value")
on any appropriate elements. element.SetAttributeValue("value", value")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.