更改 simpleXML 属性名称
change simpleXML attribute name
<Root>
...
<A CHANGE_THIS="Dont_ChengeME">
<B></B>
</A>
...
</Root>
正在尝试更改元素 A 的属性名称
根据我的选择,使用 php 的 simpleXML
API。这是我所做的:
$xml = simplexml_import_dom($xmldom);
$query = "root/A[@]";
$result = $xml->xpath($query);
if(!empty($result))
$result['CHANGE_THIS'] = "Blalalalal"; //i believe this is where am doing it wrong
所有尝试都失败了。有什么想法吗?
你可以这样做:
$xml->A['changed_value'] = $xml->A['CHANGE_THIS'];
unset($xml->A['CHANGE_THIS']);
您的尝试失败的原因是
$result['CHANGE_THIS'] = "Blalalalal";
正在将字符串 "Blalalala" 分配给由 'CHANGE_THIS' 索引的数组元素。我不知道有什么更简单的方法可以有效地更改数组元素的索引,除了将元素复制到具有所需索引(即 'changed_value')的新元素中,然后取消设置原始数组元素。
这是一种方法,假设您不需要使用 XPath:
<?php
$xml = simplexml_load_file($xmldom);
$result = $xml->{'A'}->attributes();
if(!empty($result)) {
$preserve_this = $result['CHANGE_THIS'];
$result->addAttribute('Blalalalal', $preserve_this);
unset($result['CHANGE_THIS']);
}
<Root>
...
<A CHANGE_THIS="Dont_ChengeME">
<B></B>
</A>
...
</Root>
正在尝试更改元素 A 的属性名称 根据我的选择,使用 php 的 simpleXML API。这是我所做的:
$xml = simplexml_import_dom($xmldom);
$query = "root/A[@]";
$result = $xml->xpath($query);
if(!empty($result))
$result['CHANGE_THIS'] = "Blalalalal"; //i believe this is where am doing it wrong
所有尝试都失败了。有什么想法吗?
你可以这样做:
$xml->A['changed_value'] = $xml->A['CHANGE_THIS'];
unset($xml->A['CHANGE_THIS']);
您的尝试失败的原因是
$result['CHANGE_THIS'] = "Blalalalal";
正在将字符串 "Blalalala" 分配给由 'CHANGE_THIS' 索引的数组元素。我不知道有什么更简单的方法可以有效地更改数组元素的索引,除了将元素复制到具有所需索引(即 'changed_value')的新元素中,然后取消设置原始数组元素。
这是一种方法,假设您不需要使用 XPath:
<?php
$xml = simplexml_load_file($xmldom);
$result = $xml->{'A'}->attributes();
if(!empty($result)) {
$preserve_this = $result['CHANGE_THIS'];
$result->addAttribute('Blalalalal', $preserve_this);
unset($result['CHANGE_THIS']);
}