级联xpath查询无法访问指定的节点

时间:2019-06-11 12:24:38

标签: php xpath simplexml

我有一个像下面这样的XML结构作为SimpleXMLElement:

<?xml version="1.0" encoding="UTF-8"?>
<phonebooks>
    <phonebook name="phonebook">
        ...
        <contact>
            <carddav_uid>70ad8a26-21ab-4b42-b641-44a7667e802a</carddav_uid>
            <telephony>
                <number id="0" type="work">05171290</number>
                <number id="1" type="work">05171291919</number>
                <number id="2" type="work">05171292000</number>
                <number id="3" type="work">05171292010</number>
                <number id="4" type="work">05171292245</number>
                <number id="5" type="work">05171292313</number>
                <number id="6" type="work">05171292383</number>
                <number id="7" type="work">05171292617</number>
                <number id="8" type="work">05171292761</number>
            </telephony>
            <person>
                <realName>ACME Company</realName>
            </person>
        </contact>
        ...
    </phonebook>
</phonebooks>

目标是,如果carddav_uid主要和次要的电话号码匹配,则应该为该电话号码添加某些属性。第一个条件是carddav_uid,因为电话号码可能会出现在多个联系人中(例如,具有相同座机号码的不同家庭成员)

找到合适的联系人很容易:

if ($contact = $xmlTargetPhoneBook->xpath(sprintf('//contact[carddav_uid = "%s"]', $uid))) {

我认为使用xpath在节点中搜索正确的电话号码比遍历结构更容易:

if ($contact = $xmlTargetPhoneBook->xpath(sprintf('//contact[carddav_uid = "%s"]', $uid))) {
    if ($phone = $contact[0]->xpath(sprintf('/telephony/number[text() = "%s"]', $number))) {
        // check for debugging 
        print_r($phone);
        /*
        $phone->addAttribute($attribute = $value);
        */
    }
}

但我什么也没收到:

Array
(
)

我认为错了吗?

1 个答案:

答案 0 :(得分:1)

/telephony/number从文档的根目录中选择。要从上下文项(contact元素)中进行选择,请使用./telephony/number或简单地使用telephony/number