Use XPath's last()
function, which solves this very problem:
<?php
$xml = simplexml_load_file('HistoryRecord.xml');
$xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0');
$xpath = "/o:obj/o:list/o:obj[last()]/o:int[@name = 'energy_in_kwh']";
$last_kwh = $xml->xpath($xpath);
?>
Here it looks for the last inner <obj>
, and therein for the <int>
with the name of "energy_in_kwh"
.
Watch out for the namespace registration. (All your elements are part of the "http://obix.org/ns/schema/1.0"
namespace, the XPath query must reflect that.
EDIT: Note that [last()]
is equivalent to [position() = last()]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…