0

Let's say I have some XML that looks like this:

<Users>
  <User>Bob</User>
  <User>Stefania</User>
</Users>

If I wanted to select line 3, one of the ways I could do it like this using local-name():

//*[local-name()='Users']/*[local-name()='User'][1]

My question is this. Is it possible to select multiple nodes using one statement? I've tried:

//*[local-name()='Users/User'][1]

In reality, the strings would be replaced with variables. In XForms a real example would look like this:

<xf:var name="users" value="'Users"/>
<xf:var name="user" value="'User"/>
<xf:setvalue ref="//*[local-name()=$users/$user][1]" value="'Jim'"/>

But that doesn't work.

What I'd like to be able to do it something like this:

<xf:var name="users" value="'Users"/>
<xf:var name="user" value="'User"/>
<xf:var name="myPath" value="'$users/$user'"/>
<xf:setvalue ref="//*[local-name()=$myPath][1]" value="'Jim'"/>
MorganR
  • 619
  • 3
  • 11
  • 22
  • By "selecting multiple nodes", you mean you want to select both `Bob` and `Stefania`? – Sean Pianka Jul 25 '18 at 15:10
  • Nope, I mean multiple nodes in a single path. (Not 100% node is the correct terminology). See the example I just added at the end. – MorganR Jul 25 '18 at 15:11
  • The short answer is *no*, you cannot write `//*[local-name()=$users/$user]` instead of `//*[local-name()=$users]/*[local-name()=$user]`. Are you just trying to find a shorter syntax, or is there something more to it? – avernet Jul 25 '18 at 21:51
  • @avernet No, there’s nothing more to it other than to find a shorter syntax. Thank you. I’m beginning to think you’re right about there being no shorter syntax. – MorganR Jul 26 '18 at 07:38
  • Got it, then I don't see any shorter way to write `//*[local-name()=$users]/*[local-name()=$user]`. Sorry! – avernet Jul 28 '18 at 21:49

1 Answers1

3

For your XML, which is not in a namespace,

<Users>
  <User>Bob</User>
  <User>Stefania</User>
</Users>

this XPath,

//User

selects multiple nodes (elements, specifically) in a single XPath,

  <User>Bob</User>
  <User>Stefania</User> 

as requested.

The construct, *[local-name()='User'] is used to defeat namespaces, which isn't recommended. See How does XPath deal with XML namespaces? if your XML is actually in a namespace.

kjhughes
  • 106,133
  • 27
  • 181
  • 240