I'm trying to parse through a lengthy file and remove sections that I don't want. From research It appears that the OpenXml SDK was the easiest reference for manipulating and searching through the word doc. Unfortunately, it's not always consistent because I keep getting NullReferenceExceptions when trying to assign nodes like to a run object. Essentially, my program should go through the docx file and find the tags (ver 1) and then remove everything in between it and the closing tag (/ver 1). this only seems to work for some section as other sections I get the NullReferenceException and I feel it has to do with the messy formatting that MS Word uses but I don't know.
Here's the code for a particular section if anyone could help I'd Appreciate it.
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());
}
}
}
}
}
Edit
try catch with in the code ( around the 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
try catch error around entire thing
System.NullReferenceException: Object reference not set to an instance of an object
//line 114 which would be Paragraph p = (Paragraph)run.Parent; line
elems.Parentorendelems.Parentreturns anullvalue. Is it possible that they eventually represent root nodes? EDIT: Why don't you run through the debugger and see where/why it's failing, or at least to provide us with more information. - Chris Sinclair