xsl-list
[Top] [All Lists]

RE: How to write this XQuery program?

2004-09-06 07:50:23
Whether you are using XSLT 2.0 or XQuery 1.0, there are several approaches
possible:

(a) use the min() function to find the lowest price, then search for the
company whose price is equal to that value. 

(b) sort the companies in order of price, and take the first

(c) use a recursive scan of the companies, passing the lowest-price-so-far
and the cheapest-company-so-far as parameters on the recursive call.

Taking the first approach:

<xsl:function name="cheapest-company" as="element(company)">
  <xsl:param name="companies" as="element(company)*"/>
  <xsl:param name="part-id" as="xs:string"/>
  <xsl:variable name="min-price" as="xs:decimal"
    select="min($companies/parts[id=$part-id])/price)"/>
  <xsl:sequence
select="$companies[parts[id=$part-id]/price=$min-price][1]"/>
</xsl:function>

which translates directly into XQuery as:

declare function cheapest-company (
  $companies as element(company),
  $part-id as xs:string) as element(company) {
  let $min-price as xs:decimal := 
      min($companies/parts[id=$part-id])/price)
  return $companies[parts[id=$part-id]/price=$min-price][1]
}

Michael Kay

-----Original Message-----
From: Zhimao Guo [mailto:021021090(_at_)fudan(_dot_)edu(_dot_)cn] 
Sent: 06 September 2004 14:44
To: xsl-list(_at_)lists(_dot_)mulberrytech(_dot_)com
Subject: [xsl] How to write this XQuery program?

Hi, all:

Now I have three XML files, c1.xml, c2.xml, c3.xml.
Each XML file contains information of one company, and of 
parts supplied by it.
Given a part id, I want to get the company which offered this 
part with the lowest price.
How can I write this XQuery?

-----begin of source data----
c1.xml:
 <company>
  <name>CompanyA</name>
  <parts>
   <part>
    <id>p1</id>
    <price>100</price>
   </part>
   <part>
    <id>p2</id>
    <price>101</price>
   </part>
  </parts>
 </company>
c2.xml:
 <company>
  <name>CompanyB</name>
  <parts>
   <part>
    <id>p2</id>
    <price>105</price>
   </part>
   <part>
    <id>p3</id>
    <price>106</price>
   </part>
  </parts>
 </company>
c3.xml:
 <company>
  <name>CompanyC</name>
  <parts>
   <part>
    <id>p2</id>
    <price>100</price>
   </part>
   <part>
    <id>p6</id>
    <price>106</price>
   </part>
  </parts>
 </company>
-----end of source data----

-----begin of expected result----
<result>
 <part>
  <id>p2</id>
  <price>100</price>
  <company>CompanyC</company>
 </part>
</result>
-----end of expected result----

Who would like to give me a hand? Thanks very much.

best regards,
-zhimao

--+------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: 
<mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--+--