蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

XML DOM进阶:值、属性、创建与删除:独立核心实例

JAVASCRIPTWindows / Python3.12+lxml6.1.3 / Edge156 / 自有本地HTTP,PHP为独立附例xml-dom-advanced.js
xml-dom-advanced.js5 行
import {check,parse,textFile,xmlFile,put,done,text,tableCD,xhr} from './xml-browser.js';
try{
const doc=await xmlFile('books.xml'),books=doc.getElementsByTagName('book'),first=books[0],title=first.getElementsByTagName('title')[0],initial=title.textContent,lang=title.getAttribute('lang');check(initial==='HTML与语义'&&lang==='zh'&&title.nodeValue===null,'read text and attribute');title.firstChild.nodeValue='HTML现代语义';check(title.textContent==='HTML现代语义','text node change');for(const book of books)book.setAttribute('edition','first');check([...books].every(b=>b.getAttribute('edition')==='first'),'all 3 attributes');const edition=doc.createElement('edition'),value=doc.createTextNode('初版');edition.appendChild(value);first.appendChild(edition);check(edition.parentNode===first&&edition.textContent==='初版','create and append');check(doc.documentElement.firstChild.nodeType===Node.TEXT_NODE,'indentation is text');const removable=first.getElementsByTagName('author')[0];first.removeChild(removable);check(removable.parentNode===null&&!first.getElementsByTagName('author').length&&first.getElementsByTagName('title').length===1,'remove intended element');const serialized=new XMLSerializer().serializeToString(doc),again=parse(serialized);check(again.getElementsByTagName('edition')[0].textContent==='初版','roundtrip modifications');const actual={initial_title:initial,lang,changed_title:title.textContent,all_edition_attributes:3,new_child:edition.textContent,removed_author_not_whitespace:true,element_nodeValue:null,roundtrip:true};put('#operations',JSON.stringify(actual,null,2));done(actual);
}catch(error){window.mbskyError=String(error);document.querySelector('#status').textContent='运行失败:'+String(error)}
本例需在 Windows / Python3.12+lxml6.1.3 / Edge156 / 自有本地HTTP,PHP为独立附例 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows / Python3.12+lxml6.1.3 / Edge156 / 自有本地HTTP,PHP为独立附例

入口文件:projects/xml-lab/xml-dom-advanced.js

预期结果与验证条件观察提示
  • 读标题/lang、改文本、3本加属性、建edition初版、只删author、往返后修改仍在。

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:XML

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202611a539.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习