search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Home Backend Development XML/RSS Tutorial Implementation code for parsing php DOMElement to operate xml documents

Implementation code for parsing php DOMElement to operate xml documents

Dec 24, 2016 am 11:35 AM

/*<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <!-- css的样式定义,不加点。如:name{color:red;} -->
<?xml-stylesheet type="text/css" href="css.css"?>
<!-- 引入dtd文档定义文件 (根元素:班级)<!DOCTYPE 班级 SYSTEM "class.dtd" /> -->
<!-- <!DOCTYPE 班级[
<!ELEMENT 班级 (学生+)>
<!ELEMENT 学生 (名字,年龄,介绍)>
<!ELEMENT 名字 (#PCDATA)>
<!ELEMENT 年龄 (#PCDATA)>
<!ELEMENT 介绍 (#PCDATA)>
] /> -->
<班级>
<学生 number="101">
<名字>孙悟空</名字>
<名字>孙行者</名字>
<年龄>123</年龄>
<介绍><![CDATA[&*$%特殊字串^&#$&]]></介绍>
</学生>
<学生 number="10"2">
<名字>白骨精</名字>
<年龄>140</年龄>
<介绍>介绍内容</介绍>
</学生>
</班级>
*/
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$itemsNodeList = $xmldoc->getElementsbyTagName('学生');
$itemElement = $itemsNodeList->item(0);//得到第一个完整的学生信息节点
$itemChildsNodeList = $itemElement->getElementsbyTagName('名字');//得到子节点“名字”,也许有多个名字
$itemChildNode = $itemChildsNodeList->item(0);//得到第一个名字节点
echo $itemChildNode->nodeValue;//输出节点值
//封装成函数
$nodeArr = array('名字', '年龄', '介绍'); 
function getNodeVal($xmldoc, $itemsName, $nodeArr){
    $items = $xmldoc->getElementsByTagName($itemsName);
     for($i=0; $i < $items->length; $i++){
        $item = $items->item($i);
        foreach($nodeArr as $node){
            $data[$i][] = $item->getElementsByTagName($node)->item(0)->nodeValue;
        }
    } 
    return $data;
}
$data = getNodeVal($xmldoc, '学生', $nodeArr);
print_r($data);
//添加节点
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$items = $xmldoc->getElementsByTagName('班级')->item(0);//根节点
$student =  $xmldoc->createElement('学生');//创建一个新的学生节点
$stu_name = $xmldoc->createElement('名字','张三');
$stu_age = $xmldoc->createElement('年龄','15');
$stu_intro = $xmldoc->createElement('介绍','动手能力强且成绩稳定');
$items->appendChild($student);
$student->appendChild($stu_name);
$student->appendChild($stu_age);
$student->appendChild($stu_intro);
$bytes = $xmldoc->save('datas.xml'); 
echo ($bytes)? "写入了: $bytes 字节" : '保存失败';
//删除节点
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$student = $xmldoc->getElementsByTagName('学生')->item(2);//直接找到要删除的节点
$student->parentNode->removeChild($student);//父节点的删除方法
$xmldoc->save('datas.xml');
//修改节点值
$student = $xmldoc->getElementsByTagName('学生')->item(2);
$student->getElementsByTagName('年龄')->item(0)->nodeValue += 10;
$student->setAttribute('id', '110');
$xmldoc->save('datas.xml');
//应用 Xpath 查找节点
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load('dat.xml');
$xpath = new DOMXPath($xml);
$nodeList = $xpath->query('/aaa/bbb/ddd/fff');
echo $nodeList->item(0)->nodeValue;
//SimpleXML 类操作 xml
/*
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book house="清华出版">
<code>1001</code>
<price>200元</price>
<author>大明</author>
<title>天龙八部</title>
</book>
<book house="北大出版">
<code>1002</code>
<price>321元</price>
<author>张三</author>
<title>笑傲江湖</title>
</book>
<book house="人 民出版">
<code>1004</code>
<price>182元</price>
<author>李四</author>
<title>读者</title>
</book>
</books>
*/
$xml = simplexml_load_file('books.xml');
$books = $xml->book;
echo $books[1]->title . $books[1]['house'];//直接指向第二本书
foreach($xml as $item){
    echo $item->title,' ',$item['house'],'<br/>';
}


For more analysis on the implementation code of php DOMElement operation xml document, please pay attention to the PHP Chinese website for related articles!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the XML Tools plugin in Notepad  ? (Plugin Manager) How to install the XML Tools plugin in Notepad ? (Plugin Manager) Mar 05, 2026 am 12:37 AM

Notepad v8.6.1 has completely removed the PluginManager. XMLTools cannot be installed because it has not been migrated to the new plug-in system and the author has stopped updating it. Manual installation is only applicable to v8.5.7 and earlier versions. It is recommended to use built-in functions or alternatives such as VSCode.

How to convert XML to YAML for DevOps? (Configuration Management) How to convert XML to YAML for DevOps? (Configuration Management) Mar 12, 2026 am 12:11 AM

xmltodict PyYAMListhesafestcomboforDevOpsconfigfilesbecauseitpreservescomments,CDATA,namespaces,andattributesaccurately,unlikerawXML-to-YAMLtoolsorCLIutilitieslikeyqandxmllintwhichsilentlydropcriticalmetadata.

How to format and beautify XML code in Notepad  ? (Pretty Print) How to format and beautify XML code in Notepad ? (Pretty Print) Mar 07, 2026 am 12:20 AM

Notepad needs to manually install and enable the XMLTools plug-in to format XML; if the tags are messed up or the content is lost after formatting, it means that the XML itself is illegal, and there are problems such as unclosed tags or illegal characters.

How to minify XML files for faster web loading? (Performance Optimization) How to minify XML files for faster web loading? (Performance Optimization) Mar 08, 2026 am 12:16 AM

RunningminifyonXMLwithoutunderstandingitsrulesbreaksparsingoralterssemanticsbecausewhitespacecanbemeaningful;safeminificationrequiresdata-orientedXML,controlledgeneration/consumption,andstrictparserawareness.

How to convert an XML file to a Word document? (Reporting) How to convert an XML file to a Word document? (Reporting) Mar 09, 2026 am 01:05 AM

python-docx does not support direct reading of XML files. You need to use xml.etree.ElementTree or lxml to parse the XML extraction fields first, and then write them into the Document object segment by segment. Explicit declaration of prefixes is required to process namespaces, and manual manipulation of the underlying XML is required for table merging and styling. Chinese paths should be avoided when saving.

How to use Attributes vs Elements in XML? (Design Best Practices) How to use Attributes vs Elements in XML? (Design Best Practices) Mar 16, 2026 am 12:26 AM

You should use attributes to store short metadata (such as id, type), and use elements to store scalable content data; because attributes do not support namespaces, duplication, nesting, and internationalization, their parsing is error-prone and maintenance is difficult.

How to parse XML data from a URL API? (Rest Services) How to parse XML data from a URL API? (Rest Services) Mar 13, 2026 am 12:06 AM

To parse remote XML API in Python, you need to use requests to get the response and then check the status code and Content-Type. Prioritize using r.text with xml.etree.ElementTree to parse; when encountering a namespace, you need to pass the namespace dictionary; use iterparse to stream large files and clear them manually; front-end JS requires CORS support or proxy.

How to open and view XML files in Windows 11? (Beginner Guide) How to open and view XML files in Windows 11? (Beginner Guide) Mar 12, 2026 am 01:02 AM

The XML file cannot be opened by double-clicking because it is associated with Notepad by default, causing confusion in the display. You should use Notepad, VSCode or Edge instead; Edge can format and report errors, while VSCode requires the installation of extensions such as RedHatXML for normal highlighting, indentation and verification.

Related articles