发布网友 发布时间:2022-04-06 06:41
共2个回答
懂视网 时间:2022-04-06 11:03
php xml读取、编辑、删除节点
代码如下:
$doc = new DOMDocument(); $doc->load('bird_base.xml'); $root = $doc->getElementsByTagName('birdList'); $root = $root->item(0); $bird = $root->getElementsByTagName('bird'); //遍历所有 bird 节点 foreach ($bird as $rootdata) { //遍历每一个 bird 节点所有属性 $speciesID= $rootdata->getElementsByTagName('speciesID')->item(0)->nodeValue; $localName= $rootdata->getElementsByTagName('localName')->item(0)->nodeValue; $engName= $rootdata->getElementsByTagName('engName')->item(0)->nodeValue; $latinName= $rootdata->getElementsByTagName('latinName')->item(0)->nodeValue; $bird = $this->bird->get_bird_detail($speciesID); if(!empty($bird)) { //修改节点值 $rootdata->getElementsByTagName('localName')->item(0)->nodeValue = $bird['localName']; $rootdata->getElementsByTagName('engName')->item(0)->nodeValue = $bird['engName']; $rootdata->getElementsByTagName('latinName')->item(0)->nodeValue = $bird['latinName']; }else { //删除节点 $rootdata->parentNode->removeChild($rootdata); } } $doc->save('bird_base.xml'); bird_base.xml 示例 <?xml version="1.0" encoding="UTF-8"?> <birdList> <bird> <speciesID>1</speciesID> <localName>雪鹑</localName> <engName>Snow Partridge</engName> <latinName>Lerwa lerwa</latinName> </bird> <bird> <speciesID>2</speciesID> <localName>藏雪鸡</localName> <engName>Tibetan Snowcock</engName> <latinName>Tetraogallus tibetanus</latinName> </bird> </birdList>
更多相关知识,请访问PHP中文网!
热心网友 时间:2022-04-06 08:11
InputStream is = new FileInputStream("D://dom4j.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
doc.normalize();
Node node = doc.selectSingleNode("/datas/*");//查找datas下的第一个子结点的内空
node.getParent().remove(node);
OutputFormat outformat = OutputFormat.createPrettyPrint();
// xml自身的编码
outformat.setEncoding(doc.getXMLEncoding());
outformat.setIndent(true);
File targetFile = new File("D:/dom4j3.xml");
// 将xmlStr输出到目标路径,使用xml文件的头文件编码
OutputStream out = new FileOutputStream(targetFile);
XMLWriter writer = new XMLWriter(out, outformat);
// 是否转义特殊字符,默认true转义,false表示不转义
writer.setEscapeText(false);
writer.write(doc);
writer.flush();