Taking the following XML as an example:
<?xml version="1.0" encoding="UTF-8"?>
<HelloXml>
<Greeting>Hello</Greeting>
<Name>World</Name>
<FriendList>
<Friend>
<Number>1</Number>
<BestFriend id='start' />
</Friend>
<Friend>
<Number>2</Number>
<Name>Mercury</Name>
</Friend>
<Friend>
<Number>3</Number>
<BestFriend id='end' />
</Friend>
<Friend>
<Number>4</Number>
<Name>Venus</Name>
</Friend>
<!-- ... -->
<Friend>
<Number>7</Number>
<BestFriend id='start' />
</Friend>
<Friend>
<Number>8</Number>
<Name>Saturn</Name>
</Friend>
<!-- ... -->
<Friend>
<Number>11</Number>
<BestFriend id='end' />
</Friend>
<!-- ... -->
<Friend>
<Number>12</Number>
<Name>Neptune</Name>
</Friend>
</FriendList>
</HelloXml>
I need to accomplish a couple of things:
- Get all the "Friends" that are between the "BestFriend" start/end flags (note that they are siblings, not child nodes).
- Make a sequence of all the "BestFriends" that I got there.
The idea is to make an output similar to this:
<BestFriends>
<Friend number='1'>
<Name>Mercury</Name>
</Friend>
<Friend number='2'>
<Name>Saturn</Name>
</Friend>
</BestFriends>
I've tried using the next-sibling, preceeding-sibling and other logics, but so far, no luck.
Any advise is welcome.
Thanks.
EDIT: Sorry, I messed up with an "end" flag. Also, we are using XSLT 1.0.
EDIT: Now the requirement has changed, and it's more confusing than before. The situation is the same, but now the output should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<FriendList>
<Friend BestFriend="true">
<Name>Mercury</Name>
</Friend>
<Friend BestFriend="false">
<Name>Venus</Name>
</Friend>
<Friend BestFriend="true">
<Name>Saturn</Name>
</Friend>
<Friend BestFriend="false">
<Name>Neptune</Name>
</Friend>
</FriendList>
To put the requirement in words, I need to output all the "friends" without discrimination, but I need to add an attribute to differentiate the "BestFriends" from the normal ones. These BestFriends are all of those that are inside the "start/end" flags.
The previous solution provided by @michael.hor257k is really cool and helpful (thanks again man!), but my user changed the requirement :/
I have tried some modifications to the "sibling recursion" approach, also tried some "loops" (but this is not java and of course, it didn't work), and working with some variables (that in XSLT are constants, so it doesn't work either).
Any help is welcome!
<BestFriend id='start' />
but only one<BestFriend id='end' />
? What does "between the "BestFriend" start/end flags" mean if these elements do not appear pair-wise? – Martin Honnenid="end"
instead? – Jim Garrison