【问题标题】:C# Word AddIn edit CustomXmlPartsC# Word AddIn 编辑 CustomXmlParts
【发布时间】:2020-02-10 09:24:26
【问题描述】:

我正在尝试编辑 CustomXmlPart,但我不知道如何。

我试过了:

        CustomXMLParts xmlParts = Globals.ThisAddIn.Application.ActiveDocument.CustomXMLParts.SelectByNamespace(@"MyNamespace");
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlParts[1].XML);
        foreach (XmlNode mainNode in xmlDocument.ChildNodes)
        {
            foreach (XmlNode node in mainNode)
            {
                switch (node.LocalName)
                {
                    case ("SelAdrIndex"):
                        node.InnerXml = "1111";
                        break;
                }
            }
        }

但它不起作用

我知道的唯一其他方法是删除 XML 部分并添加编辑版本。

【问题讨论】:

  • 缺少类似“xmlParts.Save()”的东西来保存 xmlPart,但我找不到这样的选项。
  • 看一下CustomXMLPart对象的属性和方法。直接使用这些,而不是单独的 XML 文档。 (注意:Word API 基于 MSXML 解析器,而不是 .NET XML 库。)
  • 啊,辛迪先生。大多数属性都是只读的,所以我不能使用它们。有一些方法,可以选择一个节点,但我还是需要保存它们。

标签: xml ms-word word-addins


【解决方案1】:

CustomXMLPart 对象的属性和方法提供了直接操作自定义 XML 部件内容的能力。无需使用保存方法或类似的方法 - 操作会立即在 XML 文件中进行。

请注意,XML 功能反映的是 COM MSXML 解析器的功能,而不是 .NET Framework 的库。

示例定位一个或多个节点,然后读/写数据。

    private void btnEditCXP_Click(object sender, RibbonControlEventArgs e)
    {
        Word.Document doc = Globals.ThisAddIn.app.ActiveDocument;
        string sXML = "<?xml version='1.0' encoding='utf-8'?><books><book><title>Test 1</title><author>Me</author></book></books>";
        Office.CustomXMLPart cxp = doc.CustomXMLParts.Add(sXML);
        Office.CustomXMLNodes nds = cxp.SelectNodes("//book");
        System.Diagnostics.Debug.Print(nds.Count.ToString());
        foreach (Office.CustomXMLNode nd in nds)
        {
            Office.CustomXMLNode ndTitle = nd.SelectSingleNode("//title");
            System.Diagnostics.Debug.Print(ndTitle.Text);
            ndTitle.Text = "11111";
            System.Diagnostics.Debug.Print(ndTitle.Text);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多