XML DOM – ProcessingInstruction 对象

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. 注意事项

  1. xml 声明也是 ProcessingInstruction
    虽然它看起来特殊,但 DOM 里它就是 target 为 “xml” 的普通处理指令。
  2. 在 HTML DOM 中不存在
    HTML 文档不会把 <?xml ...?> 当作节点,ProcessingInstruction 只在 XML 文档中有意义。
  3. 序列化时会保留
    使用 XMLSerializerdoc.documentElement.outerHTML 时,处理指令会被正确输出。
   new XMLSerializer().serializeToString(doc);
   // 输出会包含所有 <?...?>
  1. IE 老版本(IE9 以前)不支持 createProcessingInstruction
    需要 polyfill 或直接操作 innerHTML(不推荐)。

6. 常见应用场景

  • 动态添加或修改 <?xml-stylesheet?> 来切换 XSL 样式表
  • 在服务器端生成 XML 时插入自定义处理指令(如 <?php ...?>, <?oxygen ...?>
  • 读取第三方 XML 文件中的特定处理指令(如 Maven 的 <?xml-model?>

总结:ProcessingInstruction 是 XML DOM 中专门用来表示 <?target data?> 这种处理指令的节点,核心就是 targetdata 两个属性,创建用 createProcessingInstruction(),操作非常直观,主要用于 XML 文档的元信息或特定处理器指令。

文章已创建 2732

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部