0

I've an XML file like this:

<tr class="station">  
  <td class="realtime"> 
    <span>
      15:11 
    </span>
  </td> 
</tr>

<tr class="station">  
  <td class="clock"> 
    15:20 
  </td> 
</tr>

<tr class="station">  
  <td class="clock"> 
    15:30 
  </td> 
</tr>

<tr class="station">  
  <td class="realtime"> 
    <span>
      15:41 
    </span>
  </td> 
</tr>

and I wanna parse it with xpath in php. The xml is been updated and parsed quite often.
I always want to get the first time (in this case 15:11)
The problem is that its not sure whether the surrounding tag is a td by class "clock" or "realtime".
If there is a so surrounding realtime, then there is a span tag within. Otherwise not.
In fact, its always the first "station"-class tag in which the information is, that matters. So is it possible to tell xpath to just evaluate within this tag?
Is there a good method for doing this in xpath?
(sry for my bad english)

2
  • There's no 15:11 in your sample? However, retrieving the first element would be trivial. If that's the complete snippet of HTML, just do //td for your xpath, which would return an array of all <td> elements, then retrieve the .innerTEXT of only the first entry in that array, which would be the very first 15:41 of your sample. Commented Feb 18, 2011 at 16:25
  • sry, ur right! the first "15:41" was meant to be "15:11". Corrected it. Commented Feb 21, 2011 at 6:20

1 Answer 1

2

In fact, its always the first "station"-class tag in which the information is, that matters. So is it possible to tell xpath to just evaluate within this tag?

With this wellformed input source:

<table>
    <tr class="station">
        <td class="realtime">
            <span>
                15:41
            </span>
        </td>
    </tr>
    <tr class="station">
        <td class="clock">
            15:20
        </td>
    </tr>
    <tr class="station">
        <td class="clock">
            15:30
        </td>
    </tr>
    <tr class="station">
        <td class="realtime">
            <span>
                15:41
            </span>
        </td>
    </tr>
</table>

This XPath expression:

/table/tr[@class='station'][1]/td

Note: Just select the element you want and use the proper DOM API method to get the string value. It doesn't matter whether there is a span element or not.

If you want to...

/table/tr[@class='station'][1]/td//text()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.