rumi
rumi

Reputation: 3298

how to write a xpath to extract a node value with conditions on both an attribute and value

Using my c# application, I need to write a xpath that checks if a node with the attribute alias has values, title or keywords, containing a string value say knowledge returns a value of node with alias, description.

My sample xml is as below. I will need the value required description from the xml

<?xml version="1.0" encoding="UTF-8"?>
<nodes>
 <node> 
   <data alias="title">knowledge is power</data>
   <data alias="description">required description</data>
   <data alias="keywords">knowledge, power</data>   
</node>

 <node> 
   <data alias="title">Another title</data>
   <data alias="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit </data>
   <data alias="keywords">Lorem, Ipsum</data>
 </node>
</nodes>

I'm trying on these lines but it does not seem to work

if (xdoc.SelectNodes("nodes/node/data[(@alias='title' or 'keywords')]/[contains(., 'knowledge')]").Count > 0)
   {
      // extract the description node value here
   }

Upvotes: 1

Views: 206

Answers (2)

Balaji
Balaji

Reputation: 1515

string[] text = new string[10];
if (xDoc.SelectNodes("nodes/node/data[@alias='title' or @alias='keywords'][contains(text(),'knowledge')]").Count > 0)
{
    var xmlNodes = xDoc.SelectNodes("nodes/node/data[@alias='title' or @alias='keywords'][contains(text(),'knowledge')]");
    int i=-1;
    foreach (XmlNode item in xmlNodes)
    {
        i++;
        text[i] = item.InnerText.ToString();
    }
}

Upvotes: 0

Polyfun
Polyfun

Reputation: 9639

You need to specify @alias on both sides of the or:

if (xdoc.SelectNodes("nodes/node/data[@alias='title' or @alias='keywords']/[contains(., 'knowledge')]").Count > 0)

Upvotes: 1

Related Questions