Get the names of children using XPATH

C

cmsaunders

I am using simpleXML in PHP with an XML file that looks something
like:

<people>
<person>
<personID>001</personID>
<forename>Jo</forename>
<surname>Bloggs</surname>
</person>
</people>

I understand that to select the above person, I use:
/people/person[personID='001']

What I want to do is, "give me the names of all elements for the
person with personID 001". This would then return, 'forename and
'surname'. It may be assumed that I do not know that 'forename' and
'surname' exist and there may be other things in there such as
'eyeColour'.

Due to the PHP version being run, I can not use simpleXML's getName()
function. Additionally, XSLT is not an alternative.

Any ideas?

Regards.
 
M

Martin Honnen

I am using simpleXML in PHP with an XML file that looks something
like:

<people>
<person>
<personID>001</personID>
<forename>Jo</forename>
<surname>Bloggs</surname>
</person>
</people>

I understand that to select the above person, I use:
/people/person[personID='001']

What I want to do is, "give me the names of all elements for the
person with personID 001". This would then return, 'forename and
'surname'. It may be assumed that I do not know that 'forename' and
'surname' exist and there may be other things in there such as
'eyeColour'.

Use an XPath alike
/people/person[personID = "001"]/*[not(self::personID)]
then iterate over the result and access the nodeName property of each node.
 
C

cmsaunders

Use an XPath alike
/people/person[personID = "001"]/*[not(self::personID)]
then iterate over the result and access the nodeName property of each node.

Doesn't XPath have anything that can do this itself?
 
M

Martin Honnen

Use an XPath alike
/people/person[personID = "001"]/*[not(self::personID)]
then iterate over the result and access the nodeName property of each node.

Doesn't XPath have anything that can do this itself?

Well
name(/people/person[personID = "001"]/*[not(self::personID)])
would give you a string with the name of the first child element not
being personID but I don't see how that would help if you want the name
of several child elements. You would still need to iterate over the
results of an expression like the one given in my first answer, then, if
you somehow don't want to use the nodeName property, you could evaluate
name(.) with each element as the context node.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top