0

I have a following XML structure:

<?xml version="1.0" encoding="utf-8"?>
<Class>
  <subjects>
  </subjects>
  <students>
    <Name>klashf</Name>
    <Name>lkashf</Name>
  </students>
  <marks>
    <english>yes</english>
    <math>yes</math>
  </marks>
</Class>

Now for e.g. I want to delete English element <english>yes</english> from it. How can I do that? I tried many things like following but I am unable to find a way to get to that node. I tried to construct a XPath to that node but unable to get there. Can nayone tell me what should be the xPath to there?

    public bool RemoveTag(string userName, string tagName)
    {
        XmlDocument newDoc = new XmlDocument();
        newDoc.Load(path);

        XPathNavigator navigator = newDoc.CreateNavigator();
        XPathExpression query = navigator.Compile("//marks");
         query = navigator.Compile("//marks/" + tagName);

        XmlNodeList marksNodes = newDoc.GetElementsByTagName("marks");
        XmlNode nodeToDelete=marksNodes[0].SelectSingleNode(userName+"/marks/"+tagName);
        for (int i = 0; i < marksNodes.Count; i++)
        {
            marksNodes[i].RemoveChild(nodeToDelete);
        }
        return status;
    }
Lynn Crumbling
  • 12,985
  • 8
  • 57
  • 95
Maven
  • 14,587
  • 42
  • 113
  • 174

1 Answers1

-1

I prefer to use XDocument over XmlDocument. (using System.Xml.Linq)

XDocument doc = XDocument.Load(path);
foreach(XElement elment in doc.Root.Descendants("english").ToArray())
    elment.Remove();

This deletes all occurences of the element "english" regardless of their position.

A more precise approach:

foreach(XElement markElement in doc.Root.Elements("marks"))
{
    foreach(XElement englishElement in markElement.Elements("english").ToArray())
        english.Remove();
}

this does not involve any xpath, so this is an alternativ solution to your problem.

CSharpie
  • 9,195
  • 4
  • 44
  • 71