简体   繁体   English

删除所有没有属性的XML元素C#

[英]Remove all XML elements with no attributes C#

I would like to know how to remove all elements from an xml file which do not have a first attribute of type name or ref . 我想知道如何从xml文件中删除所有没有第一个名称nameref的属性的元素。 The child elements that DO contain a first attribute of the required type must stay even if the parent has been deleted and they should just be moved up in the hierarchy 包含必需类型的第一个属性的子元素必须保留,即使父元素已被删除,它们也应在层次结构中向上移动

For example, if this is the input file: 例如,如果这是输入文件:

<xs:element name="Body" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="Client" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Risk" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Claim" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Complaint" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="ClientFee" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="User" minOccurs="0" />
    </xs:sequence>
  </xs:complexType>
</xs:element>

I would expect the following output: 我期望以下输出:

<xs:element name="Body" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element ref="Client" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Risk" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Claim" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="Complaint" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="ClientFee" minOccurs="0" maxOccurs="unbounded" />
      <xs:element ref="User" minOccurs="0" />
</xs:element>

For example this way: 例如这种方式:

 void RemoveRecurence(XElement e) {
      foreach(var child in e.Elements()) {
           RemoveRecurence(child);
      }

      if (e.Attribute("name") == null && e.Attribute("ref") == null) {
           e.ReplaceWith(e.Elements());            
      }
 }

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

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