打开XML文字内容控件 [英] Open XML word content controls
问题描述
这是我的代码试图获取带有标签"company"的内容控件
Here is my code trying to get the content controls with the tag "company"
using (WordprocessingDocument template = WordprocessingDocument.Open("d:/dev/ProposalTemplate1.dotx", true))
{
MainDocumentPart mainPart = template.MainDocumentPart;
SdtBlock block = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "TEST").Single();
Text t = block.Descendants<Text>().Single();
t.Text = "COMPANY_NAME";
}
由于查询行,出现错误对象引用未设置为对象的实例",但我不知道为什么...
I got the error "Object reference not set to an instance of an object" because of the query line but I don't know why...
当我创建一个仅带有一个内容控件的简单模板,而使用较大的Word模板时,此效果很好
This works well when I create a simple template with just one content controls but not when using a bigger word template
有什么主意吗?
编辑
我尝试在没有.Single()
的情况下执行此操作,但仍无法正常工作
EDIT
I try doing it without .Single()
but still not working
MainDocumentPart mainPart = template.MainDocumentPart;
var blocks = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "Company");
foreach (SdtBlock block in blocks)
{
Text t = block.Descendants<Text>().Single();
t.Text = "COMPANY1";
}
编辑2
我更改了Text.Single()
问题仍然存在,SdtBlock block = ...
行上的对象引用未设置为对象的实例"
EDIT 2
I change the Text.Single()
The problem is still there "Object reference not set to an instance of an object" on the SdtBlock block = ...
line
MainDocumentPart mainPart = template.MainDocumentPart;
var blocks = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "Company");
foreach (SdtBlock block in blocks)
{
var t = block.Descendants<Text>();
foreach (Text text in t)
{
text.Text = "COMPANY1";
}
}
推荐答案
并非所有SdtBlock
元素都具有子Tag
元素.您假设其中一个存在,并尝试访问Val
属性,但这样做会得到空引用异常.
Not all SdtBlock
elements have child Tag
elements. You are assuming one exists and attempting to access the Val
property but are getting a null reference exception in doing so.
您可以通过在Where
谓词中检查是否为空来解决此问题:
You can fix it by checking for null within the Where
predicate:
var blocks = mainPart.Document.Body.Descendants<SdtBlock>().Where(r =>
{
var tag = r.SdtProperties.GetFirstChild<Tag>();
return tag != null && tag.Val == "Company";
});
根据评论,我的在此处中提供了有关您最初使用Single
时遇到的问题的更多信息.
As per the comments there is more information about the issues you originally had with using Single
in my answer here.
这篇关于打开XML文字内容控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!