简体   繁体   中英

Removing element from XML in C# with an attribute

I m new into C#. I m trying to delete the element having attribute name = "companyKey"

I have tried to do so through the following code:

XElement xml = XElement.Parse(results);
xml.Elements("NewDataSet")
   .Attributes("companyKey").Remove();

DataSet ds = new DataSet();
using (var reader = xml.CreateReader())
ds.ReadXml(reader);

However, It is not excluding/deleting the element. Any help/clue would be appreciated.

The XML I m using to apply this code is:

<NewDataSet>
 <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
   <xs:complexType>
    <xs:choice minOccurs="0" maxOccurs="unbounded">
     <xs:element name="Table1">
      <xs:complexType>
       <xs:sequence>
            <xs:element name="companyKey" type="xs:string" minOccurs="0" />      
            <xs:element name="phoneVisits" type="xs:int" minOccurs="0" />
       </xs:sequence>
      </xs:complexType>
     </xs:element>
    </xs:choice>
   </xs:complexType>
  </xs:element>
 </xs:schema>

Elements will only return the child elements from the current node, not the children's children (otherwise known as descendants). You then select and remove the attribute , not the element. As that child element and attribute don't exist, you have an empty sequence so nothing is removed.

What you want to do is find all descendant elements where the element contains your name attribute. Try:

XNamespace xs = "http://www.w3.org/2001/XMLSchema"

xml.Descendants(xs + "element")
    .Where(x => (string)x.Attribute("name") == "companyKey")
    .Remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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