0
votes

My record.xml looks like :

<record>
    <name>john</name>
    <gender>male</gender>
    <subject>mathematics, english, science</subject>
</record>
<record>
    <name>jamie</name>
    <gender>female</gender>
    <subject>mathematics, science</subject>
</record>
<record>
    <name>jamie</name>
    <gender>female</gender>
    <subject>social-science, english</subject>
</record>

I want to write a xpath query which will return record node containing one or more given subjects.

For Example :

If want to get record of student with subject mathematics and science

then second record should be returned i.e.

<record>
    <name>jamie</name>
    <gender>female</gender>
    <subject>mathematics, science</subject>
</record>

This is what i did till now :

<?php
        $xmldoc = new DOMDocument();
        $xmldoc->load('record.xml');

        $xpathvar = new Domxpath($xmldoc);

        $res = $xpathvar->query('//record/subject[. = "science"]');
        foreach($res as $data){
                echo $data->textContent.'<br>';
        }
?>

I want to Achieve Result Something Like this :

<?php
        $xmldoc = new DOMDocument();
        $xmldoc->load('record.xml');

        $xpathvar = new Domxpath($xmldoc);

        $res = $xpathvar->query('//record/subject[. = "science" and mathematics]');
        foreach($res as $data){
                echo $data->textContent.'<br>';
        }
?>
1
What issue are you running into? What PHP library are you using? - chris85
@chris85 I updated question - Ajay

1 Answers

1
votes

There really isn't going to be a nice way to acheive this unless you can split up the subjects into their own nodes.

/r/record[contains(subject,"science") and contains(subject,"mathematics") and ...  ]

The does nothing to determine where the word are split, so if you have a subject, say, "computer science" then you'll get a false hit. You'll be better off of you can split the subject text into seperate elements.

 <record>
   <name>jamie</name>
   <gender>female</gender>
   <subject>mathematics</subject>
   <subject>science</subject>
</record>

xpath =  /r/record[subject[.="science" and .="mathematics" ... and ...] ]

or have a some form of word breaks delimiter like so:

 <record>
   <name>jamie</name>
   <gender>female</gender>
   <subject>|mathematics|science|</subject>
</record>

xpath = /r/record[contains(subject,"|science|") and contains(subject,"|mathematics|") and ...  ]