简体   繁体   中英

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?

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.

我不认为有一种将属性与通配符匹配的方法,但是您可以使用contains方法,例如:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM