问题
I am running an xpath query on an xml stream and retreiving a set of data. In that i need to find the tag name. But im not able to find the way to retrieve the tag name. The xml stream is
<Condition>
<Normal dataItemId="Xovertemp-06" timestamp="2011-09-02T03:35:34.535703Z" name="Xovertemp" sequence="24544" type="TEMPERATURE"/>
<Normal dataItemId="Xservo-06" timestamp="2011-09-02T03:35:34.535765Z" name="Xservo" sequence="24545" type="LOAD"/>
<Normal dataItemId="Xtravel-06" timestamp="2011-09-02T03:35:34.535639Z" name="Xtravel" sequence="24543" type="POSITION"/>
</Condition>
I am trying to parse this as
Temperature = Normal
Load - Normal
So what i did is
foreach ($xml->xpath("//n:Condition")->children("n") as $child) {
echo $child["type"] . "=" . $child->getName();
}
I am getting the followin error
Fatal error: Call to a member function children() on a non-object in C:\xampp\htdocs\DataDumper\datadumper\test.php on line 53
Now i know this has got something to do with the way i query the xpath or something and i tried various combination such as adding an * slash to the query but the same error every time.
回答1:
Not sure why you used namespace notaion in the first place(the sample xml is not namespaced)
In your xpath, you need to select all condition/normal
tags, not the condition
tag as you were doing...
Also, xpath()
returns a list, so foreach
over it. You don't need to access it as children, unless you want to parse the children of $child
. There it would make sense, and it would work as expected.
foreach ($xml->xpath("/Condition/Normal") as $child) {
echo $child["type"] . "=" . $child->getName()."<br/>";
}
outputs
TEMPERATURE=Normal
LOAD=Normal
POSITION=Normal
回答2:
The problem is due to SimpleXMLElement::xpath() returning an array and not a SimpleXMLElement
. I'm also not sure about the namespace support in the XPath query however I'm sure you can fiddle with that to work it out. In any case, I see no n
namespace in your XML.
The answer really depends on how many elements you expect to match your XPath query. If only one, try
$conditions = $xml->xpath('//Condition');
if (count($conditions) == 0) {
throw new Exception('No conditions found');
}
$condition = $conditions[0];
foreach ($condition->children() as $child) {
printf('%s = %s', (string) $child['type'], $child->getName());
}
来源:https://stackoverflow.com/questions/7279638/finding-children-in-php-simplexml-xpath