5

在 samplexml.svg 中有一个节点

<image width="744" height="1052" xlink:href="image1.png"/>

我需要用“image2.png”之类的另一个值替换“image1.png”。请用示例代码指导我如何做到这一点。

我可以获得属性值“image1.png”。这是代码:

$xdoc = new DomDocument;
$xdoc->Load('samplexml.svg');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

这是samplexml.svg:

<svg>
    <g>
        <title>Test title</title>
        <image x="0" y="0" width="744" height="1052" xlink:href="image1.png"/>
    </g>
</svg>

如何以编程方式更改 xlink:href 值?

4

1 回答 1

13

使用DOMElement::setAttributeNS()

$xdoc = new DomDocument;
$xdoc->Load('svg.xml');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

$tagName->setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'image2.png');

echo $xdoc->saveXML();
于 2010-05-18T12:29:03.023 回答