0

I have a xml file

<?xml version="1.0" encoding="UTF-8"?> <xml> <settings> <title>Calendar for September</title> <subTitle>Calendar for September Calendar for September</subTitle> </settings> <events date="06-09-2010"> <event id="2"> <title>This is My Second Event</title> <description>This is My Second Event </description> </event> <event id="3"><title>This is My Third Event </title><description>This is My Third Event This is My Third Event This is My Third Event </description></event></events> </xml> 

I am parsing the xml file using

$xml_str = file_get_contents('xmlfile'); $xml = simplexml_load_string($xml_str); if(!empty($xml)) { $nodes = $xml->xpath('//xml/events/event[@id="'.$id.'"]'); } 

It will give only the title and description of event tag with specified id.How i can get the date

2 Answers 2

1

Try

//event[@id="2"]/parent::events/@date 

Together with the original XPath:

//event[@id="2"]/parent::events/@date | //event[@id="2"] 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks KennyTM.But it will give only date.
@THOmas: You could | with the original XPath.
@THOmas: //event[@id="2"]/parent::events/@date | //event[@id="2"]
@KennyTM: Two minor: whenever schema is well know, try to avoid starting // operator, the abbreviated syntax .. is also well know. So this could be: /*/*/event[@id='2']|/*/*/event[@id='2']/../@date. Also, with "context free" expresion is a good practice to select in one direction only like /*/events[event[@id='2']]/@date.
0

Once you've found the <event> element use it as the context node for a new xpath query that fetches the nearest <events> element in the ancestor-axis.

$id = 2; $xml = simplexml_load_file('xmlfile'); if( !$xml ) { echo '!xml doc'; } else if ( !($event=$xml->xpath('events/event[@id="'.$id.'"]')) ) { echo '!event[id=...'; } else if ( !($container = $event[0]->xpath('ancestor::events[1]')) ) { echo '!events parent'; } else { echo $container[0]['date'], ' - ', $event[0]->title, "\n"; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.