A
A
Angelxalfa2015-09-22 17:39:17
PHP
Angelxalfa, 2015-09-22 17:39:17

How to properly parse XML through Xpath?

Good afternoon! There is an xml like this:

<street street="улица1">
    <house house="1">
      <appartment appartment="1"/>
      <appartment appartment="2"/>
      <appartment appartment="4"/>
    </house>
    <house house="8">
      <appartment appartment="1"/>
      <appartment appartment="2"/>
      </house>
     </street >
<street street="улица2">
    <house house="1">
      <appartment appartment="1"/>
      <appartment appartment="2"/>
      <appartment appartment="4"/>
    </house>
    <house house="8">
      <appartment appartment="1"/>
      <appartment appartment="2"/>
      </house>
     </street >

I need to select apartments only in a specific building on a specific street (in real XML there are hundreds of streets and thousands of houses).
I select houses on a certain street through xpath, I pass the received through a loop and get houses
$xml = simplexml_load_file('file.xml');
            $names = $xml->xpath("//street[@street='".$street."']");
            foreach($names as $street) {
              foreach($street->house as $house) {
                $house_num = $house[house];
                echo '<option value="' . $house_num . '">' . $house_num . '</option>'; 
              }

Question. How to do the same for apartments. If you insert a search by apartments into the same cycle, the same apartments will be repeated according to the number of selected xpath houses. Is it possible to select a house through x-path, where attribute = something, which is in the street tag, where attribute = something ....
Something like
$xml->xpath("//house[@house='".$house."' AND ../street[@street='".$street."']]");

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
throughtheether, 2015-09-22
@Angelxalfa

It's not quite clear what exactly you want to get (at least on the example of your test XML).
Expression of the form

//street[@street="baker street"]/house[@house="221B"]/appartment
should select all apartments of the specified building on the specified street. If you need rooms, add /@appartment to the end.
A p artment, by the way. And it seems redundant to duplicate node names with attribute names.
Is it possible to select a house through x-path, where attribute = something, which is in the street tag, where attribute = something....
Using the axis ancestor or, if the relationship is direct, parent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question