Joseph Thompson
Joseph Thompson

Reputation: 76

Selecting a specific node in xml file

This is my Xml Document called device.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Device DeviceInfo="443">
    <Settings>
        <Section Name="CustomData">
            <Entry Name="InstitutionName" Value=""></Entry>
            <Entry Name="DeviceSerialNumber" Value=""></Entry>
        </Section>
        <Section Name="ExternalTools">
            <Entry Name="Printers and Faxes" ShellPath="control printers" Service="True"></Entry>
            <Entry Name="Task Manager" ShellPath="taskmgr" Service="True"></Entry>
            <Entry Name="Control Panel" ShellPath="control" Service="True"></Entry>
            <Entry Name="Notepad" ShellPath="notepad" Service="True"></Entry>
            <Entry Name="Paint" ShellPath="mspaint" Service="True"></Entry>
            <Entry Name="Command Prompt" ShellPath="cmd" Service="True"></Entry>
            <Entry Name="Google Search" ShellPath="&quot;%ProgramFiles%\Internet Explorer\iexplore.exe&quot; http://www.google.com" Service="True"></Entry>
        </Section>
        <Section Name="ResearchTools"></Section>
    </Settings>
</Device>

I am trying to Delete the printer and faxes section, and later, the command prompt. I cannot figure out the syntax for selecting a single node. This is what I have:

using System;
using System.Xml;

namespace ExternalToolsUpdateScript
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlPath = "D:\\Device\\device.xml";

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(xmlPath);
            XmlNode node = xmlDocument.SelectSingleNode("Settings/Section[Entry = 'Printers and Faxes']");

            node?.ParentNode?.RemoveChild(node);
            xmlDocument.Save(xmlPath);
        }
    }
}

I can either get it to delete mostly everything for entry names or nothing but not that single entry line. What am I doing wrong please? Please note that I am a Junior still learning.

Upvotes: 1

Views: 114

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

It would be easiest to use Linq to Xml to do this:

var xml = XDocument.Load("D:\\Device\\device.xml");

xml.XPathSelectElement("Device/Settings/Section/Entry[@Name = 'Printers and Faxes']")
  ?.Remove();

You can use either XPathSelectElement or XPathSelectElements depending on whether you want to find and remove a single node or potentially more than one, respectively.

Note that your original XPath query was missing a root element, and the element selector syntax was wrong. I corrected these issues in the version above.

You'll need to make sure the System.Xml.Linq assembly is referenced, and you'll need to import the System.Xml.Linq and System.Xml.XPath namespaces.

Upvotes: 1

Related Questions