PHP和XPath按条件获得不同的属性

时间:2018-03-26 11:52:58

标签: php xpath

我正在使用PHP来解析XML,并希望使用XPATH根据系统和前端值条件返回唯一的部分值。

XML:

<?xml version="1.0" encoding="utf-8"?>
<language>
    <phrase section="Url" system="0" front="1" data="_URL_M1">invoice</phrase>
    <phrase section="Url" system="0" front="1" data="_URL_M2">view</phrase>
    <phrase section="Invoice" system="1" front="0" data="_MOD_IM1">System1</phrase>
    <phrase section="Invoice" system="1" front="0" data="_MOD_IM2">System2</phrase>
    <phrase section="Invoice" system="0" front="1" data="_MOD_IM3">Front1</phrase>
    <phrase section="Invoice" system="0" front="1" data="_MOD_IM4">Front2</phrase>
    <phrase section="Invoice" system="1" front="1" data="_MOD_IM5">System and Front</phrase>
</language>

所以我的部分Url只显示在前面= 1和部分Invoice的位置,显示前面= 1,前面和系统(两者)= 1。需要显示部分明显。

PHP:

$xmlel = simplexml_load_file(BASEPATH . self::langdir . $flag . "/" . $filename . ".xml");

$query_system = '/language/phrase[@system="1" and @front="0" and not(@section = preceding-sibling::phrase/@section)]/@section';

$query_front = '/language/phrase[@system="0" and @front="1" and not(@section = preceding-sibling::phrase/@section)]/@section';

$query_both = '/language/phrase[@system="1" and @front="1" and not(@section = preceding-sibling::phrase/@section)]/@section';

使用当前代码,我得到了这个:

系统:$xmlel->xpath($query_system)

Array
(
[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Invoice
            )

    )
)

正面:$xmlel->xpath($query_front)

Array
(
[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Url
            )

    )
)

两者:$xmlel->xpath($query_both)

Array
(
)

我想要实现的目标:

系统:

Array
(
[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Invoice
            )

    )
)

前:

Array
(
[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Url
            )

    )
)
[1] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Invoice
            )

    )
)

这两种:

Array
(
[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [section] => Invoice
            )

    )
)

如何获得明确的section
其中:system = 1,
其中front = 1
以及systemfront = 1

的位置

1 个答案:

答案 0 :(得分:0)

好的,所以我得出结论,我还需要调整前兄弟:

$query_system = '/language/phrase[@system="1" and @front="0" and not(@section = preceding-sibling::*[@system="1" and @front="0"]/@section)]/@section';
$query_front = '/language/phrase[@system="0" and @front="1" and not(@section = preceding-sibling::*[@system="0" and @front="1"]/@section)]/@section';
$query_both = '/language/phrase[@system="1" and @front="1" and not(@section = preceding-sibling::*[@system="1" and @front="1"]/@section)]/@section';