Marshall Tigerus
Marshall Tigerus

Reputation: 3764

Using XPath with node attributes

I have the very basics of XPaths down, but am having some trouble in determining if the following is possible in C# code using an XPath (or if I need to move it out into other code, as I currently have done).

I have an XML Document that consists of the following structure:

 <xml>
     <parameters>
        <setParameter name="SomeName" value="SomeValue" />
     </parameters>
 </xml>

Where there are multiple set Parameter values. Now what I need to do is only retrieve those setParameter nodes that contain certain values for the name attribute. I may have a list of possible matches for these values, but they won't be full matches, they will be values the node's name attribute must contain.

For example in the structure code above, if I had a value of 'men' to match, it would come back with the node, as 'men' is contained in 'SomeName'

What is the shorthand to do this?

Upvotes: 0

Views: 94

Answers (3)

Andersson
Andersson

Reputation: 52685

Depending on your XPath version this might work or might not:

//setParameter[matches(@name,"men", "i") or matches(@name,"else", "i")]

This should match <setParameter> with name attribute that contains "men" or something "else". It is case-insensitive

Try and let me know the result

Upvotes: 0

eLRuLL
eLRuLL

Reputation: 18799

I don't think there is a way to match an attribute with a wildcard, but you could use the contains method, something like:

//parameters/setParameter[contains(@name, "stringexample")]

Upvotes: 0

Kilazur
Kilazur

Reputation: 3188

Retrieving the value of all attributes named value for all elements named setParameter having a name attribute's value containing men:

//setParameter[contains(@name, 'men')]/@value
  • //setParameter

Retrieves all nodes named setParameter (can be replaced with /xml/parameters/setParameter)

  • [...]

Checks an attribute for the current node selection

  • contains(@name, 'men')

Returns true if the name attribute's value contains men

  • /@value

Retrieves the value attribute's value.

Upvotes: 1

Related Questions