将customXML部件添加到Word

时间:2018-09-03 11:46:26

标签: c# ms-word openxml

我正在尝试向Word添加自定义XML部件。我正在做的是生成一个XML模型,该模型将Word文件中的所有数据绑定在一起。这是我尝试填充的方式,但未添加任何内容:

public void FeedCustomXmlParts(MyModel model, string xmlns)
{
    var ser = new XmlSerializer(typeof(MyModel), xmlns);
    using (var ms = new MemoryStream())
    {
        ser.Serialize(ms, model);
        CustomXmlPart partLabel = GetCustomXmlPart(_wordDoc.MainDocumentPart, xmlns);
        ms.Position = 0;
        partLabel.FeedData(ms);
        ms.Flush();
    }
}

private static CustomXmlPart GetCustomXmlPart(MainDocumentPart mainDocumentPart, string targetNs)
{
    if (mainDocumentPart == null)
    {
        throw new ArgumentNullException(nameof(mainDocumentPart));
    }

    return (from part in mainDocumentPart.CustomXmlParts
        let xElement = part.GetXDocument().Root
        where xElement != null
        let ns = xElement.GetDefaultNamespace()
        where ns == targetNs
        select part).FirstOrDefault();
}

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

根据您的描述,我了解您想在单词中添加自定义XML部分。

下面的代码示例将自定义XML部件添加到指定的文档。

    private void AddCustomXmlPartToActiveDocument(Word.Document document)
{
    string xmlString =
        "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
        "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
            "<employee>" +
                "<name>Karina Leal</name>" +
                "<hireDate>1999-04-01</hireDate>" +
                "<title>Manager</title>" +
            "</employee>" +
        "</employees>";

    Office.CustomXMLPart employeeXMLPart = document.CustomXMLParts.Add(xmlString, missing);
}

有关更多信息,请参阅:To add a custom XML part to a Word document

希望有帮助!