user2058253
user2058253

Reputation: 301

Deletion of a single node in xml using c#

My xml file is as follows:

   <Default>
      <CareSettingName>
         <Name>Hosp1/Name>
         <Name>Hosp2/Name>
         <Name>Hosp3/Name>
         <Name>Hosp4/Name>
       </CareSettingName>
      <DocNames>
         <Name>Doc1/Name> 
         <Name>Doc2/Name> 
         <Name>Doc3/Name> 
        </DocNames>
    </Default>

With the following code I try to delete Hosp4:

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load(localXMLfile);
 XmlNode node = xmlDoc.SelectSingleNode("/Default/CareSettingName[Name='Hosp4']");

 node.ParentNode.RemoveChild(node);
 xmlDoc.Save(localXMLfile);

When I run this, it deletes ALL the entries in CareSettingName - not the single one I am looking for. I can't see to find the problem. Can somebody please help me?

Can anybody please help me? Thanks.

Upvotes: 1

Views: 60

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52888

It's because you're selecting /Default/CareSettingName (when it contains a Name that equals Hosp4).

Try changing your xpath to:

/Default/CareSettingName/Name[.='Hosp4']

Upvotes: 2

Related Questions