我正在PHP中尝试为XML文件的<gpx>
元素添加一个额外的命名空间。这是现有的<gpx>
元素(注意,不包括名称空间“ stunninghikes”):
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1"
xmlns:gpsies="https://www.gpsies.com/GPX/1/0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
creator="GPSies https://www.gpsies.com - Amden - Chapf (1296m) - Arvenb&#252;el - Vorderh&#246;hi - Gulmen (1788m) - Hinter H&#246;hi - Niederschlag"
version="1.1"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd https://www.gpsies.com/GPX/1/0 https://www.gpsies.com/gpsies.xsd">
<content>
(Lots more content)
</content>
</gpx>
我想要将属性xmlns:stunninghikes="https://stunninghikes.com/GPX/1/0"
添加到<gpx>
元素中。
我尝试了使用createAttributeNS
和setAttributeNS
的多种选择,但无法正常工作!这是我尝试过的一个例子:
$gpxDoc = new DomDocument;
$gpxDoc->load($gpxFileName);
$gpxNode = $gpxDoc->getElementsByTagName('gpx');
$gpxNode->createAttributeNS('https://stunninghikes.com/GPX/1/0', 'xmlns:stunninghikes');
$gpxDoc->appendChild($gpxNode);
有什么想法吗?
答案 0 :(得分:1)
您的尝试非常接近。不允许您手动更改文档的xmlns
属性,相反,您会收到DOMException
抱怨“命名空间错误”。
您可以做的是创建一个属性(任何属性),并且XML文档将自动更新为包括名称空间,即使您没有将其附加到文档中也是如此:
$gpxDoc = new DomDocument;
$gpxDoc->load($gpxFileName);
$gpxDoc->createAttributeNS('https://stunninghikes.com/GPX/1/0', 'stunninghikes:dummy');
echo $gpxDoc->saveXML();
输出:
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpsies="https://www.gpsies.com/GPX/1/0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stunninghikes="https://stunninghikes.com/GPX/1/0" creator="GPSies https://www.gpsies.com - Amden - Chapf (1296m) - Arvenb&#252;el - Vorderh&#246;hi - Gulmen (1788m) - Hinter H&#246;hi - Niederschlag" version="1.1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd https://www.gpsies.com/GPX/1/0 https://www.gpsies.com/gpsies.xsd">
<content>
(Lots more content)
</content>
</gpx>