0

我最近问了一个关于如何使用 xpath同时选择父节点属性及其值的问题,我最终得到的是:

Parent/@attr|Parent/x

它获取 parentattr的值及其所有x节点..

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [attr] => attrValue
                )
        )

    [1] => SimpleXMLElement Object
        (
            [0] => 1
        )

    [2] => SimpleXMLElement Object
        (
            [0] => 2
        )

    [3] => SimpleXMLElement Object
        (
            [0] => 3
        )

)

现在的事情..如果有几个Parent节点,它将把它们混合在一起,我不知道哪个attr属于它x的..它会产生这样的结果:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [attr] => attrValue
                )
        )

    [1] => SimpleXMLElement Object
        (
            [0] => 1
        )

    [2] => SimpleXMLElement Object
        (
            [0] => 2
        )

    [3] => SimpleXMLElement Object
        (
            [0] => 3
        )

    [4] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [attr] => anotherAttrValue
                )
        )

    [5] => SimpleXMLElement Object
        (
            [0] => 1
        )

    [6] => SimpleXMLElement Object
        (
            [0] => 2
        )

    ...
)

您会看到,它们都被视为正常结果,我要做的是将其attr所有结果( 1, 2, 3 )包含在一个数组或其他东西中,而同样的事情也将传递给attr另一个最终得到这样的结果:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [attr] => attrValue
                )
        )
        Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => 1
                )

            [1] => SimpleXMLElement Object
                (
                    [0] => 2
                )

            [2] => SimpleXMLElement Object
                (
                    [0] => 3
                )
        )

    [1] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [attr] => anotherAttrValue
                )
        )
        Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => 1
                )

            [1] => SimpleXMLElement Object
                (
                    [0] => 2
                )

            [2] => SimpleXMLElement Object
                (
                    [0] => 3
                )
        )
)

使用 xpath 和最初给出的方式

4

0 回答 0