1

I've been trying to wrap my head around using XPath and XQuery for this with the help of some previous posts to no avail. Right now I have null child nodes which should just default to ordering at the end of a sort but unfortunately, the sort does not occur at all on these null nodes. As a result I have been trying to find a way to set them to zero during the sorting section. Here is a sample below:

<xsl:for-each select="MyItems/Item">
<xsl:sort select="Order/obj/Number" order="ascending"> 

I want to do something similar to an inline if statement as part of the sort like in C# below:

foreach(item in MyItems.OrderBy(Order/obj/Exists != false ? Order/obj/Number : 0)

I was using these links: dynamic xpath expression and XSLT transfom with inline if statements to try and understand but I'm still not getting it. Any help is appreciated. I need the solution in XSLT.

Community
  • 1
  • 1
GFXGunblade
  • 97
  • 3
  • 10
  • I assume there are multiple `Order/obj` elements for each `Item` element? If so those `Item` elements will be sorted by the `Number` of the first `Order/obj` in the `Item`. Which child nodes are coming up as null? It sound like you have some empty `Item` nodes? – Borodin May 30 '12 at 18:54

2 Answers2

2

Your situation is unclear as you say nothing about the contents of your XML or the nature of your XSLT transform. But it sounds something like you have Item elements with no Order/obj/Number elements to sort on?

I would code that something like this

<xsl:template match="/root">

  <xsl:copy>

    <xsl:apply-templates select="MyItems/Item[Order/obj/Number]">
      <xsl:sort select="Order/obj/Number" />
    </xsl:apply-templatesh>

    <xsl:apply-templates select="MyItems/Item[not(Order/obj/Number)]" />

  </xsl:copy>

</xsl:template>

<xsl:template select="MyItems/Item">
  <xsl:copy-of select="current()" />
</xsl:template>
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Data is being serialized from a code behind, so the xml is generated on the fly. As far as your comment above goes, the obj level is an abstraction class to contain basic item types, Exist (a boolean), Number (an integer). I knew some Order level nodes were null of the item type so I was looking for a way to check if they were on the fly. I found my solution tweaking what I have but this is a good second, thank you. – GFXGunblade May 30 '12 at 19:59
0

Talking about "null nodes" isn't helpful. It's not a well-defined term. Show us your XML, your desired results and your actual results, and we can help you.

What should happen is that if the select expression in xsl:sort returns an empty sequence/node-set, the effective sort key is a zero-length string, so these items sort before any others (assuming ascending order).

Michael Kay
  • 156,231
  • 11
  • 92
  • 164