简体   繁体   中英

php xml generation with xpath

I wrote a small helper function to do basic search replace using xpath, because I found it easy to write manipulations very short and at the same time easy to read and understand.

Code:

<?php
function xml_search_replace($dom, $search_replace_rules) {
    if (!is_array($search_replace_rules)) {
        return;
    }

    $xp = new DOMXPath($dom);

    foreach ($search_replace_rules as $search_pattern => $replacement) {
        foreach ($xp->query($search_pattern) as $node) {
            $node->nodeValue = $replacement;
        }
    }
}

The problem is that now I need to do different "search/replace" on different parts of the XML dom. I had hoped something like the following would work, but DOMXPath can't use DOMDocumentFragment :(

The first part (until the foreach loop) of the example below works like a charm. I'm looking for inspiration for an alternative way to go around it which is still short and readable (without to much boiler plate).

Code:

<?php
$dom = new DOMDocument;
$dom->loadXml(file_get_contents('container.xml'));
$payload = $dom->getElementsByTagName('Payload')->item(0);

xml_search_replace($dom, array('//MessageReference' => 'SRV4-ID00000000001'));

$payloadXmlTemplate = file_get_contents('payload_template.xml');
foreach (array(array('id' => 'some_id_1'),
               array('id' => 'some_id_2')) as $request) {
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML($payloadXmlTemplate);
    xml_search_replace($fragment, array('//PayloadElement' => $request['id']));

    $payload->appendChild($fragment);
}

Thanks to Francis Avila I came up with the following:

<?php
function xml_search_replace($node, $search_replace_rules) {
    if (!is_array($search_replace_rules)) {
        return;
    }

    $xp = new DOMXPath($node->ownerDocument);

    foreach ($search_replace_rules as $search_pattern => $replacement) {
        foreach ($xp->query($search_pattern, $node) as $matchingNode) {
            $matchingNode->nodeValue = $replacement;
        }
    }
}

$dom = new DOMDocument;
$dom->loadXml(file_get_contents('container.xml'));
$payload = $dom->getElementsByTagName('Payload')->item(0);

xml_search_replace($dom->documentElement, array('//MessageReference' => 'SRV4-ID00000000001'));

$payloadXmlTemplate = file_get_contents('payload_template.xml');
foreach (array(array('id' => 'some_id_1'),
               array('id' => 'some_id_2')) as $request) {
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML($payloadXmlTemplate);
    xml_search_replace($payload->appendChild($fragment),
                       array('//PayloadElement' => $request['id']));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM