1

拥有下一个 XML(Idatzi.xml) :

<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
<markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
<markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
<markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>

以及下一个 PHP 代码:

<?php

$xmlIdatziDok = new DOMDocument();
if($xmlIdatziDok->load("Idatzi.xml") === FALSE){die('Error');}
$xPath_IdatziDok = new DOMXPath($xmlIdatziDok);

foreach ($xPath_IdatziDok->query('//markables/markable') AS $Idaztekoa)
{
  $IdaztekoaID = $Idaztekoa->getAttribute('id');
  $IdaztekoaAtrib = $Idaztekoa->getAttribute('atrib');

    if($IdaztekoaAtrib != "yes")
    {
      $Idazteko->Attribute('atrib') = "yes";      
    }
}

我想知道如何在PHP代码中正确编写下一行代码:

$Idazteko->Attribute('atrib') = "yes";

明显写错了。我想做的是将markable_2的“否”更改为“是”。任何的想法?

4

2 回答 2

4

您可以在文档中找到此信息。

$Idaztekoa->setAttribute('atrib', 'yes');
于 2012-04-24T12:18:22.400 回答
0

使用 xpath 查询直接选择您想要更改和操作的所有属性:

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

并做了。完整示例:

$xml = <<<XML
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
    <markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
    <markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
    <markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXPath($doc);

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

echo $doc->saveXML();
于 2012-04-24T19:57:31.523 回答