将具有属性的所有元素设置为某个值


Setting all elements with attribute to a certain value

我正试图将属性为"布尔"的给定XML文件的ALL元素的值设置为True,我很难弄清楚如何做到这一点:

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($sxe->asXML());
    $xpath = new DOMXPath($dom);
    foreach ($xpath->query('//*[@type="Boolean"]') as $node) {
             // something to set the value of $node to the value of "True"
             }
    echo $dom->saveXML();

我试过:

$node->{0} = value; // does not actually replace values but doesn't error
$node[0] = value; // errors  Cannot use object of type DOMElement as array

另外,如果有人知道,我如何告诉DOM不要使用简写输出XML?

您正试图更改attribute值,因此请使用setAttribute

foreach ($xpath->query('//*[@type="Boolean"]') as $node) {
             $node->setAttribute('type', 'True');
             }

更新:

foreach ($xpath->query('//*[@type="Boolean"]') as $node) {
                 $node->nodeValue = 'true';
                 }

对于你的空标签问题,我假设生成这些标签的代码不在你发布的内容中,但在创建/添加新元素时,使用空参数,而不是完全删除它,即:

addChild('elementname', '')

而不是

addChild('elementname')