Reputation: 173
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>
Upvotes: 0
Views: 1331
Reputation: 26223
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();
Upvotes: 1