您当前的位置: 首页 > 学无止境 > XML与XSLT 网站首页XML与XSLT
4.节点的删除与替换
发布时间:2017-04-30 12:44:49编辑:雪饮阅读()
节点的删除与属性的删除:
php:
<?php
$dom=new DOMDocument('1.0','utf-8');
$dom->load('./08.xml');
//获得animal节点
$animal=$dom->getElementsByTagName('animal')->item(0);
//获得animal节点下的color节点(待删除)
$color=$dom->getElementsByTagName("color")->item(0);
$animal->removeChild($color);
$animal->removeAttribute('id');
header("content-type:text/xml;charset=utf-8");
echo $dom->saveXML();
?>
08.xml:
<?xml version="1.0" encoding="utf-8"?>
<animal id='1' data='puwu'>
<name weight="50" height="20">dog</name>
<color>yellow</color>
<age>2</age>
<intro><![CDATA[very<g>ood]]></intro>
</animal>
节点的替换:
<?php
//节点的替换
$dom=new DOMDocument('1.0','utf-8');
$dom->load('./08.xml');
//待替换节点设为节点1
$age=$dom->getElementsByTagName("age")->item(0);
//创建新节点(用来替换节点1)
$sex=$dom->createElement("sex");
$sex_txt=$dom->createTextNode("g");
$sex->appendChild($sex_txt);
//实现节点替换
$age->parentNode->replaceChild($sex,$age);
header("content-type:text/xml;charset=utf-8");
echo $dom->saveXML();
?>
注意:如果用已有节点(设为节点1)来替换另外一个已有节点(设为节点2),则节点2消失,节点1移动到原节点2的位置.
关键字词:php,xml,节点
上一篇:3.xml的创建
下一篇:5.rss介绍与rss制作