Jthunter24
Jthunter24

Reputation: 57

Why won't XQUERY output just the variable and not all of the elements beneath it?

I am very new to Xquery and am very confused about a principle. I am trying to output a variable that is written in my XML document but every time I try to output the variable all of the nodes underneath it output as well. Here is my XML:

<PurchaseOrders>
  <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
    <Address Type="Shipping">
      <Name>Ellen Adams</Name>
      <City>Seattle</City>
    </Address>
    <Address Type="Billing">
      <Name>Tai Yee</Name>
      <City>Denver</City>
    </Address>
  </PurchaseOrder>

  <PurchaseOrder PurchaseOrderNumber="99505" OrderDate="1999-10-22">
    <Address Type="Shipping">
      <Name>Cristian Osorio</Name>
      <City>Seattle</City>
    </Address>
  </PurchaseOrder>
 </PurchaseOrders>

And I would like my output to be:

<Orders>
  <Order>
    <Name>Ellen Adams</Name>
    <OrderID>99503<OrderID>
  </Order>
  <Order>
    <Name>Cristian Osorio</Name>
    <OrderID>99505</OrderID>
  </Order>

Here is my XQuery

<Orders> {
  for $purchaseOrder in /PurchaseOrders/PurchaseOrder[Address/@Type='Shipping']
    let $shippingAddress := $purchaseOrder/Address[@Type='Shipping']
    where $shippingAddress/City ='Seattle'
    return <order> {$shippingAddress/Name} {$purchaseOrder[@PurchaseOrderNumber]}</order>
  }
  </Orders>

But when I run it I get (This is just an example for one person):

<Orders>
  <order>
    <Name>Cristian Osorio</Name>
    <PurchaseOrder PurchaseOrderNumber="99505" OrderDate="1999-10-22">
      <Address Type="Shipping">
        <Name>Cristian Osorio</Name>
        <City>Seattle</City>
      </Address>
      <Address Type="Billing">
        <Name>Cristian Osorio</Name>
        <City>Seattle</City>
      </Address>
    </PurchaseOrder>
  </order>

Why can't I just output the variable PurchaseOrderNumber without all of the other information attached to it?

Thanks for your help!

Upvotes: 0

Views: 116

Answers (1)

dirkk
dirkk

Reputation: 6218

The good news is: You can absolutely do this. You are currently just doing it wrong. When you define {$purchaseOrder[@PurchaseOrderNumber]} it means to give all purcharse orders which do habe a purchase order number. [] is a predicate, so just to filter out elements in your result set. If you want the attribute value you can do a path step as you did in other parts of your query:

{$purchaseOrder/@PurchaseOrderNumber}

However, outputting attributes directly is not necessarily defined, so you most likely want to use just the attribute value. Also, as an attribute does not have a surrounding element you will have to do

<OrderID>{$purchaseOrder[@PurchaseOrderNumber]/string()}</OrderID>

to get your desired result.

Upvotes: 3

Related Questions