You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Word Online移除Custom XML Parts,getByNamespaceAsync返回空求解决方案

问题解答

getByNamespaceAsync是否支持Word Online?

getByNamespaceAsync函数完全支持Word Online,你遇到的空结果问题并非函数本身不兼容,而是Word Online对Custom XML Parts的存储规则和桌面版存在差异:

Word Online会自动清理未与文档内容(如内容控件、XML绑定元素)关联的独立Custom XML Parts,只有那些和文档可视化元素绑定的XML部件才会被保留并能通过API获取。而桌面版Word允许存在不绑定任何内容的独立XML部件。

替代方案

1. 将Custom XML Parts与内容控件绑定

把XML部件的节点绑定到文档中的内容控件(可以设置为隐藏状态,不影响文档正常显示),这样Word Online会保留该XML部件。示例代码:

// 创建或获取目标Custom XML部件
Office.context.document.customXmlParts.getByNamespaceAsync("http://your-namespace", function(result) {
  if (result.status === Office.AsyncResultStatus.Succeeded && result.value.length > 0) {
    var xmlPart = result.value[0];
    // 创建隐藏的内容控件并绑定XML节点
    Office.context.document.body.insertContentControlAsync(
      "",
      {hidden: true},
      function(ccResult) {
        if (ccResult.status === Office.AsyncResultStatus.Succeeded) {
          var contentControl = ccResult.value;
          // 绑定到XML部件的指定节点
          contentControl.bindXmlAsync(xmlPart, "/root/data", function(bindResult) {
            if (bindResult.status === Office.AsyncResultStatus.Succeeded) {
              console.log("XML部件已绑定到内容控件,Word Online将保留");
            }
          });
        }
      }
    );
  }
});

2. 使用Office.js Settings对象存储数据

如果你的数据不需要复杂的XML结构,只是键值对形式,Settings对象是跨平台的理想选择,数据会随文档保存:

// 存储数据
Office.context.document.settings.set("your-key", "your-value");
Office.context.document.settings.saveAsync(function(saveResult) {
  if (saveResult.status === Office.AsyncResultStatus.Succeeded) {
    console.log("数据已保存");
  }
});

// 获取数据
var value = Office.context.document.settings.get("your-key");

3. 利用自定义文档属性

对于简单的字符串数据,自定义文档属性也是跨平台支持的选项:

// 设置自定义属性
Office.context.document.properties.customProperties.setAsync("customProp", "propValue", function(setResult) {
  if (setResult.status === Office.AsyncResultStatus.Succeeded) {
    console.log("自定义属性已设置");
  }
});

// 获取自定义属性
Office.context.document.properties.customProperties.getAsync("customProp", function(getResult) {
  if (getResult.status === Office.AsyncResultStatus.Succeeded) {
    console.log("属性值:" + getResult.value);
  }
});

内容的提问来源于stack exchange,提问作者Zen Lang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 10:57:38