XML DOM 中的 ProcessingInstruction 对象
ProcessingInstruction(处理指令)是 XML DOM 中一种节点类型,它代表 XML 文档中的处理指令(Processing Instruction,简称 PI),常见的例子就是:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<?php echo 'Hello'; ?>
<?cocoon-process type="xslt"?>
其中 <?xml ...?> 和 <?xml-stylesheet ...?> 都是 ProcessingInstruction 节点。
1. 节点类型常量
在 JavaScript(浏览器环境)中:
node.nodeType === 7 // Node.PROCESSING_INSTRUCTION_NODE
2. 主要属性
| 属性 | 说明 | 只读 |
|---|---|---|
| nodeName | 返回处理指令的 target(目标名),如 “xml”、”xml-stylesheet”、”php” | 是 |
| nodeValue | 返回处理指令的内容(target 之后的所有字符,不包含 ),可能为 null | 否 |
| textContent | 同 nodeValue(在 ProcessingInstruction 中等价) | 否 |
| target | 等同于 nodeName,返回处理指令的目标名称 | 是 |
| data | 等同于 nodeValue,返回或设置内容 | 否 |
| ownerDocument | 所属的 Document 对象 | 是 |
| parentNode | 父节点(通常是 Document 或 DocumentFragment) | 是 |
3. 示例 XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="style.css"?>
<root>
<item>内容</item>
</root>
4. JavaScript 操作示例
// 假设 doc 是已经解析好的 XML Document 对象
const doc = new DOMParser().parseFromString(xmlString, "text/xml");
// 获取所有处理指令
const pis = doc.processingInstructionNodes ||
Array.from(doc.childNodes).filter(n => n.nodeType === 7);
pis.forEach(pi => {
console.log("target:", pi.target); // 如 "xml", "xml-stylesheet"
console.log("data:", pi.data); // 如 "version="1.0" encoding="UTF-8""
console.log("nodeValue:", pi.nodeValue); // 同 data
});
// 获取第一个处理指令(通常是 xml 声明)
const xmlDeclaration = doc.childNodes[0]; // 大概率是 <?xml ...?>
if (xmlDeclaration.nodeType === 7) {
console.log(xmlDeclaration.target); // "xml"
console.log(xmlDeclaration.data); // 'version="1.0" encoding="UTF-8"'
}
// 创建新的处理指令
const newPI = doc.createProcessingInstruction(
"xml-stylesheet",
'type="text/xsl" href="transform.xsl"'
);
console.log(newPI.target); // "xml-stylesheet"
console.log(newPI.data); // 'type="text/xsl" href="transform.xsl"'
// 插入到文档最前面(常用于插入 xml-stylesheet)
doc.insertBefore(newPI, doc.firstChild);
// 修改已有处理指令内容
xmlDeclaration.data = 'version="1.0" encoding="GB2312" standalone="yes"';
5. 注意事项
- xml 声明也是 ProcessingInstruction
虽然它看起来特殊,但 DOM 里它就是 target 为 “xml” 的普通处理指令。 - 在 HTML DOM 中不存在
HTML 文档不会把<?xml ...?>当作节点,ProcessingInstruction 只在 XML 文档中有意义。 - 序列化时会保留
使用XMLSerializer或doc.documentElement.outerHTML时,处理指令会被正确输出。
new XMLSerializer().serializeToString(doc);
// 输出会包含所有 <?...?>
- IE 老版本(IE9 以前)不支持 createProcessingInstruction
需要 polyfill 或直接操作 innerHTML(不推荐)。
6. 常见应用场景
- 动态添加或修改
<?xml-stylesheet?>来切换 XSL 样式表 - 在服务器端生成 XML 时插入自定义处理指令(如
<?php ...?>,<?oxygen ...?>) - 读取第三方 XML 文件中的特定处理指令(如 Maven 的
<?xml-model?>)
总结:ProcessingInstruction 是 XML DOM 中专门用来表示 <?target data?> 这种处理指令的节点,核心就是 target 和 data 两个属性,创建用 createProcessingInstruction(),操作非常直观,主要用于 XML 文档的元信息或特定处理器指令。