Gentle
Gentle

Reputation: 87

Delete element with a specific attribute

As i said in the title :

I want to delete the whole element when i do not get "preRequisite" in the attribute:

(XML) First Element:

  <dependency>
     <dependentAssembly dependencyType="install">
     </dependentAssembly>
  </dependency>

(XML) Second Element:

<dependency>
     <dependentAssembly dependencyType="preRequisite">
     </dependentAssembly>
  </dependency>

Current Code:

private void Deletepopulates()
    {
        filepath = "C:\Folder\Exaple.exe.manifest"
        XmlDocument doc = new XmlDocument();
        doc.Load(filepath);
        foreach(var nodeToDelete in new List<XmlNode>(doc.SelectNodes(filepath + "[@dependencyType!='preRequisite']").Cast<XmlNode>()))
        {
            if (nodeToDelete != null)
            {
                nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
            }
        doc.Save(filepath);
        }
    }

Current it does only delete the Child (dependencyType) but it shall delete the element (dependency), is there a way to delete dependency ?

and at: new List<XmlNode>(doc.SelectNodes(filepath + "[@dependencyType!=preRequisite").Cast<XmlNode>())i get an Exception called: System.Xml.XPath.XPathException

Hopfully its clear otherwhise i'll edit it in your favor :)

Upvotes: 0

Views: 61

Answers (1)

MarioDS
MarioDS

Reputation: 13063

Your XPath is invalid in 2 ways:

  1. Missing closing bracket ].

  2. You forgot to put single quotes around preRequisite. Actually not having the single quotes around preRequisite is valid but it doesn't do what you want it to do. It searches a preRequisite child node and compares its value to the dependencyType attribute.

The rest of your code looks okay, and I expect it to do what you want once you correct the XPath. It should look like this:

filepath + "[@dependencyType!='preRequisite']"

Important: The filepath variable must also be valid XPath of course. Now it looks like it holds a file path, which can never make for valid XPath.

What you want, I guess, is just this:

doc.SelectNodes("//dependentAssembly[@dependencyType!='preRequisite']")

Upvotes: 2

Related Questions