C# Word AddIn 编辑 CustomXmlParts

C# Word AddIn edit CustomXmlParts

我正在尝试编辑 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 部分并添加编辑版本。

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

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

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

    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);
        }
    }