Home > OS >  C# XML Select single sub node in node by value
C# XML Select single sub node in node by value

Time:02-04

I have the following problem, I want to select the book with the author "Johnny Dapp33", which unfortunately does not work.

XML Code:

<employees xmlns:bar="http://www.bar.org">
    <employee id="Test1">
        <name>Johnny Dapp</name>
        <author>Al Pacino</author>
    </employee>
     <employee id="Test2">
        <name>Johnny Dapp33</name>
        <author>Al Pacino</author>
    </employee>
</employees>

I would have tried it via ".SelectSingleNode", unfortunately I always fail with the XPath.

Thank you for your help!

CodePudding user response:

Let's say we have a file called Employees.xml in our project directory.

We can load the xml file in our memory by using this assignment:

XmlDocument doc = new XmlDocument();
doc.Load("Employees.xml");

Second we try to find a single node (presuambly) by its id in a structure employees/employee (this is our path), no we have to add the search param (id in this case) like this:

XmlNode singleNode = doc.SelectSingleNode("/employees/employee[@id='Test1']");
Console.WriteLine(singleNode.OuterXml);

However if we only know the name we are looking for we can also search for that specific value like this. We search in the employee node for the node value of name with the value of Johnny Dapp33:

XmlNode singleNode = doc.SelectSingleNode("descendant::employee[name='Johnny Dapp33']");
Console.WriteLine(singleNode.OuterXml);

CodePudding user response:

While dealing with XMl, it is better to use LINQ to XML API.

It is available in the .Net Framework since 2007.

c#

void Main()
{
    const string filePath = @"e:\Temp\WizardZZ.xml";
    XDocument xdoc = XDocument.Load(filePath);
        
    var employee = xdoc.Descendants("employee")
      .Where(d => d.Elements("name").FirstOrDefault().Value.Equals("Johnny Dapp33"));
      
     Console.WriteLine(employee);
}

Output

<employee id="Test2">
  <name>Johnny Dapp33</name>
  <author>Al Pacino</author>
</employee>

CodePudding user response:

If you need to use XPath (and there must be a very strong reason for it), you can use it with XElement:

var xml = """
<employees xmlns:bar="http://www.bar.org">
    <employee id="Test1">
        <name>Johnny Dapp</name>
        <author>Al Pacino</author>
    </employee>
     <employee id="Test2">
        <name>Johnny Dapp33</name>
        <author>Al Pacino</author>
    </employee>
</employees>
""";

var x = XElement.Parse(xml);
var employees = x.XPathSelectElements("/employee[name='Johnny Dapp33']");

if (employees is not null)
{
  foreach (var employee in employees)
  {
    WriteLine((string)employee.Element("name") ?? "[name] not found");
  }
}
else
{
  WriteLine("did not find any employees");
}
  • Related