如何编写一个xQuery来根据其他值的条件提取两个字段?

时间:2018-02-15 20:19:23

标签: xpath xquery xpath-2.0 xquery-3.0

我有一个XML文档:

GET /payments

我想使用FLWOR编写一个xQuery来提取emp_no和first_name,其中emp_no是10001,其中的coressponding名字如下:

<resultsets>
    <row>
        <emp_no>10001</emp_no>
        <first_name>Georgi</first_name>
        <last_name>Facello</last_name>
    </row>
    <row>
        <emp_no>10002</emp_no>
        <first_name>Bezalel</first_name>
        <last_name>Simmel</last_name>
    </row>
</resultset>

我写的代码:

<row>
     <emp_no>10001</emp_no>
     <first_name>Georgi</first_name>
</row>

然而,它返回$ id和$ first的笛卡尔积,

for $id in doc("employees.xml")//emp_no
for $first in doc("employees.xml")//first_name
where ($id/text() = '10001')
return 
    <row>
    <id>{upper-case($id/text())}</id>
    <first>{$first/text()}</first>
    </row> 

你知道如何使用xQuery FLWOR解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我只需选择emp_no,然后在for $row in /resultsets/row where $row/emp_no = '10001' return <row> <id>{$row/emp_no/data()}</id> <first>{$row/first_name/data()}</first> </row> 孩子上使用where子句:

emp_no

http://xqueryfiddle.liberty-development.net/bFukv89

目前尚不清楚是否要将元素名称从id更改为first_name以及从first更改为for $row in /resultsets/row where $row/emp_no = '10001' return <row> {$row/emp_no, $row/first_name} </row> ,如果不需要,您可以当然只需复制它们:

class InputRepository
{
    private $db;
    protected $mappers = array();

    public function __construct($db, array $mappers) {
        $this->db = $db;
        $this->mappers = $mappers;
    }

    public function getMapper($key) {
        if (!isset($this->mappers[$key]) {
           throw new Exception('Invalid mapper "'. $key .'"');
        }

        if (!$this->mappers[$key] instanceof MapperInterface) {
           $this->mappers[$key] = new $this->mappers[$key]($this->db);
        }

        return $this->mappers[$key];
    }

    public function getCountry()
    {
        $mapper = $this->getMapper('country');
        $country = $mapper->fetch();
        return $country; //returns country object
    }
    // lots of other methods for returning different model objects
}

http://xqueryfiddle.liberty-development.net/bFukv89/1