使用简单的XML (php更改一个属性)



我有一个字符串形式的xml输入,我想查看它并找到一个特定的元素并修改它。

我感兴趣的xml输入部分是这样的,它是字符串

中层次结构的一部分
<com:GTe Type="GTe" xmlns:com="http://xyx.com/Gte">
    <com:Cd ED="2021-07" Number="0123456789"/>
</com:GTe>

ED元素各不相同,所以我只对识别所有具有Number属性的com:Cd子元素感兴趣,然后将Number属性的最后三位数字更改为另一个字符串。

该项目使用Symfony和简单的XML php,但我不确定如何做到这一点,因为XML的其他部分使用其他数据的数字键。

试过下面的

 $message = 
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq
         <com:GTe Type="GTe" xmlns:com="http://xyx.com/Gte">
             <com:Cd ED="2021-07" Number="0123456789"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>';
    $xmlstring = simplexml_load_string($message);
    //currently not working
    $number = $xmlstring->soapenv:Envelope->soapenv:Body->uv:HCRReq->com:GTe->com:CD->number;
    $length = strlen($number);
    //need to check length is 11 or 12 long
    $alteredNum = '1234567'.substr($number,length-3,3);
// Not sure how to set the string

你可以试试这个吗:

$message =
    '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq>
         <com:GTe Type="GTe" xmlns:com="http://xyx.com/a">
             <com:Cd ED="2021-07" Number="012345678999"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>';
$xml = simplexml_load_string($message);
$nodes = $xml->xpath('//*[name()="com:Cd" and @Number]');
if ($nodes) {
    $number = (string)$nodes[0]->attributes()['Number'];
    if (12 === strlen($number) || 11 === strlen($number)) {
        unset($nodes[0]->attributes()['Number']);
        $nodes[0]->addAttribute('Number', '111' . substr($number, -3, 3));
    }
}
print_r($xml->asXML());

结果:

<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq>
         <com:GTe xmlns:com="http://xyx.com/a" Type="GTe">
             <com:Cd ED="2021-07" Number="111999"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>

虽然看起来<uv:HCRReq xml开始标记缺少>,但这可能是复制粘贴问题。

最新更新