我試圖通過一個冗長的文件解析並刪除我不想要的部分。從研究看來,OpenXml SDK是操縱和搜索word doc最簡單的參考。不幸的是,它並不總是一致的,因爲在嘗試將節點分配給運行對象時,我總是收到NullReferenceExceptions
。實質上,我的程序應該通過docx文件並找到標籤(版本1),然後刪除它與結束標籤(/版本1)之間的所有內容。這似乎只適用於其他部分的某些部分,我得到NullReferenceException
,我覺得它與MS Word使用的混亂格式有關,但我不知道。在DOCX文件上使用OpenXML的Constant NullReference異常
下面是特定部分的代碼,如果有人可以幫助我欣賞它。圍繞整個事情
IEnumerable<OpenXmlElement> elem = main.Document.Body.Descendants().ToList();
foreach (OpenXmlElement elems in elem)
{
if (elems is Text && elems.InnerText == s_Ver1)// s_Ver1 = "(Ver 1)"
{
Run run = (Run)elems.Parent;
Paragraph p = (Paragraph)run.Parent;
p.RemoveAllChildren();
p.Remove();
foreach (OpenXmlElement endelems in elem)
{
if (endelems is Text && elems.InnerText == e_Ver1)//e_Ver1 = "(/Ver1)"
{
run = (Run)endelems.Parent;
p = (Paragraph)run.Parent;
p.Remove();
break;
}
else
{
Run d_Run = (Run)endelems.Parent;
Paragraph d_p = (Paragraph)d_Run.Parent;
d_p.RemoveAllChildren();
d_p.Remove();*/
try
{
endelems.Remove();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
}
}
}
}
編輯
嘗試捕捉與代碼中(圍繞endelems.remove())
System.InvalidOperationException: The Parent of this element is Null
//it also says line 141 but I'm not sure how to get line numbering in vs2010
嘗試捕捉錯誤
System.NullReferenceException: Object reference not set to an instance of an object
//line 114 which would be Paragraph p = (Paragraph)run.Parent; line
我猜某處'elems.Parent'或'endelems.Parent'返回'null'值。它們有可能最終代表根節點嗎?編輯:你爲什麼不運行調試器,看看它在哪裏/爲什麼失敗,或者至少爲我們提供更多信息。 – 2013-04-23 21:02:29
哪些線路例外? – Romoku 2013-04-23 21:05:32
你可以用try-catch來包圍整個事物併發布錯誤嗎? – devilfish17 2013-04-23 23:55:05