简体   繁体   English

C#XML-将属性复制到子元素

[英]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: 好吧,我会:

  • Load the XML into an XDocument 将XML加载到XDocument
  • Find <element2> using doc.Descendants("element2").First() or doc.Root.Element("element2") 使用doc.Descendants("element2").First()doc.Root.Element("element2")查找<element2>
  • Find the attribute value you'll want to copy, eg with string value = (string) element.Attribute("value"); 找到您要复制的属性值,例如,使用string value = (string) element.Attribute("value");
  • Iterate over all all <element3> elements using doc.Root.Elements("element3") 使用doc.Root.Elements("element3")所有<element3>元素
  • Test each <element3> for children with element.Element("element4") != null 使用element.Element("element4") != null为孩子测试每个<element3> element.Element("element4") != null
  • Call element.SetAttributeValue("value", value") on any appropriate elements. 在任何适当的元素上调用element.SetAttributeValue("value", value")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM