Chengjun Guo
Chengjun Guo

Reputation: 13

How to find XML element by the pattern of attribute’s value

I need to search XML element by the pattern of the value of an attribute.

The current XML file I’m working on looks like:

<root>
   <items>
      <item Id=“001” name=“Foo001”></item>
      <item Id=“002” name=“Foo002”></item>
      <item Id=“003” name=“Boo001”></item>
   </items>
</root>

I need to search for the element that the value of its name attribute starts with “Boo”

I’ve tried to use the following code (found on google) to search but it is not working

XmlDocument doc = new XmlDocument();
doc.Load(myXmlFilePath);
XmlNode match = doc.SelectSingleNode(“/root/items/item[substring(@name,1,3)=‘Boo’]”);
Console.WriteLine(match.Value.ToString());

Could anyone show me how to implement what I needed in C# please?

Upvotes: 0

Views: 790

Answers (1)

EylM
EylM

Reputation: 6103

You are using the wrong quotes in both, your XML and the XPATH.

  • Change “ to "" in your XML

  • Change ‘ to ' in your XPATH

    <root>
     <items>
         <item Id="001" name="Foo001"></item>
         <item Id="002" name="Foo002"></item>
         <item Id="003" name="Boo001"></item>
     </items>
    </root>
    
    XmlNode match = doc.SelectSingleNode("/root/items/item[substring(@name,1,3)='Boo']");
    

In order to read the results:

// read the attribute name
Console.WriteLine(match.Attributes["name"].Value);

// read the text in item        
Console.WriteLine(match.InnerText);

Upvotes: 2

Related Questions