XML

查询工具

使用辅助函数遍历和检查已解析的 XML Element 树

使用 parse() 解析 XML 后,用这些工具函数遍历和提取 Element 树中的数据。

查找子元素

findChild

按标签名查找第一个直接子元素:

import { parse, findChild } from "@office-open/xml";

const root = parse("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const run = findChild(root, "w:r");

children

获取所有匹配标签名的直接子元素:

import { parse, children } from "@office-open/xml";

const root = parse("<w:p><w:r/><w:r/><w:r/></w:p>");
const runs = children(root, "w:r"); // 3 个元素

allChildren

获取所有直接子元素(不限制标签名):

import { allChildren } from "@office-open/xml";

const all = allChildren(root);

读取文本

childText

获取第一个匹配子元素的文本内容:

import { parse, findChild, childText } from "@office-open/xml";

const root = parse("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const text = childText(root, "w:t"); // "Hello"

textOf

获取元素本身的文本内容:

import { textOf } from "@office-open/xml";

const textEl = findChild(run, "w:t");
const text = textOf(textEl); // "Hello"

collectText

收集元素及其后代中所有文本节点的内容:

import { collectText } from "@office-open/xml";

const allText = collectText(paragraph); // 连接的文本内容

读取属性

attr

获取字符串类型的属性值:

import { parse, findChild, attr } from "@office-open/xml";

const element = parse('<w:spacing w:before="240" w:after="120"/>');
attr(element, "w:before"); // "240"
attr(element, "w:after"); // "120"

attrNum

获取数字类型的属性值:

attrNum(element, "w:before"); // 240

attrBool

获取布尔类型的属性值:

attrBool(element, "w:val"); // 根据 "true"/"1"/"false"/"0" 返回

colorAttr

获取规范化后的十六进制颜色属性:

import { colorAttr } from "@office-open/xml";

colorAttr(element, "w:color"); // "FF0000"

检查结构

hasChild

检查元素是否包含特定子元素:

import { hasChild } from "@office-open/xml";

hasChild(paragraph, "w:pPr"); // true 或 false

findDeep

查找所有匹配标签名的后代元素:

import { findDeep } from "@office-open/xml";

const allTextNodes = findDeep(document, "w:t");

childCount

获取直接子元素数量:

import { childCount } from "@office-open/xml";

childCount(paragraph); // 3

完整参考

函数返回值说明
findChild(parent, name)Element | undefined按名称查找第一个直接子元素
children(parent, name)Element[]按名称查找所有直接子元素
allChildren(parent)Element[]所有直接子元素
childText(parent, name)string第一个匹配子元素的文本
textOf(element)string元素的文本内容
collectText(element)string所有后代的文本内容
attr(element, name)string | undefined字符串类型属性值
attrNum(element, name)number | undefined数字类型属性值
attrBool(element, name)boolean | undefined布尔类型属性值
colorAttr(element, name)string | undefined十六进制颜色属性
hasChild(parent, name)boolean子元素是否存在
findDeep(parent, name)Element[]按名称查找所有后代元素
childCount(parent)number直接子元素数量
Copyright © 2026