0

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>
3
  • 4
    "It is not working" is not enough information for us to help you. Please review How to Ask. Commented Dec 31, 2015 at 19:11
  • I'm confused. If you're trying to delete the element with name="companyKey", then why does your code delete the operatorImageUrl attribute in any root NewDataSet element? Commented Dec 31, 2015 at 19:17
  • Sorry, I have corrected it. I want to delete the element with the name="companyKey" Commented Dec 31, 2015 at 19:19

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.