deucalion0
deucalion0

Reputation: 2440

How to correctly use XML attributes when using XSLT

I made an XML file an example of which is here:

  <flight flightid="1">
<flightno>EK98</flightno>
<callsign>UAE98</callsign>
<airline>Emirates Airline</airline>
<altitude height="feet">41000 feet</altitude>
<speed ratio="mph">564 mph</speed>
<plane planeid="1">
  <name>Airbus 330</name>
  <speed>567 mph</speed>
  <wingspan>199 ft 11 in</wingspan>
  <length>301 ft 7 in</length>
  <registereddate>07-06-10</registereddate>
</plane>
<route>
  <routename>Fiumicino-Dubai</routename>
  <course bearing="degrees">154 degrees</course>
  <distance unit="miles">2697 miles</distance>
  <duration>PT5H30M</duration>
  <from>
    <iatacode>FCO</iatacode>
    <airport>Fiumicino</airport>
    <country>Italy</country>
    <city>Rome</city>
    <latitude>41.8044</latitude>
    <longitude>12.2508</longitude>
    <yahoowoeid>715520</yahoowoeid>
  </from>
  <to>
    <iatacode>DXB</iatacode>
    <airport>Dubai Intl</airport>
    <country>UAE</country>
    <city>Dubai</city>
    <latitude>25.2528</latitude>
    <longitude>55.3644</longitude>
    <yahoowoeid>1940345</yahoowoeid>
  </to>
</route>
</flight>

In the distance element you can see the unit for miles:

<distance unit="miles">2697 miles</distance>

In the text I have written miles, I felt that the point in attributes was so that I can use that and output the value of the attribute alongside the value in distance? Here is a sample of my XSL where distance is used and my attempt at adding units:

<tr>
  <td><xsl:attribute name="class">lside</xsl:attribute>Distance</td>
  <td colspan="2"><xsl:attribute name="class">rside</xsl:attribute><xsl:value-of select="/flights/flight/route[routename/. ="Fiumicino-Dubai"]/distance"/><xsl:value-of select="@unit" /></td>
</tr>

While I ask this question, is my initial intention the correct way to use attributes, is this why attributes exist, so as to create a global type of say measurement which will always be the same?

Upvotes: 0

Views: 93

Answers (1)

Magnum
Magnum

Reputation: 1595

An attribute is essentially a short form of element-value pair in an XML document. Thus <distance unit="miles">2697 miles</distance> would be the same as writing the following:

<distance>
    <unit>
        <value>miles</value>
    </unit>
    <value>2697</value>
</distance>

Yes, you are using the element attribute correctly in your above XML. You may choose to form your XML document anyway you wish--and therefore pull the information of such accordingly.

Transfering answer in the comments below into the answer:

To access the value of an element with a specific attribute using XPath, use the below to distinguish:

"/flights/flight/route[routename/. ="Fiumicino-Dubai"]/distance/@unit=@miles

Upvotes: 1

Related Questions