Search code examples
c#ms-wordopenxmlopenxml-sdkwordprocessingml

How to remove elements from a document?


Is there a way to iterate through a document and remove all <:p /> elements if they don't have any runs? I am trying to remove paragraphs if they look something like this:

<w:p>
    <w:pPr>
        <w:pStyle w:val="Heading1" />
        <w:numPr>
            <w:ilvl w:val="0" />
            <w:numId w:val="0" />
        </w:numPr>
        <w:ind w:left="432" />
    </w:pPr>
</w:p>

Here is what I have so far, but it only removes empty <w:p /> elements.

foreach (Paragraph P in D.Descendants<Paragraph>().Where(x => !x.HasChildren).ToList()

Solution

  • You can call this :

    foreach (Paragraph P in D.Descendants<Paragraph>()
             .Where(o=>o.Descendants<Run>().Count() ==0).ToList()
    

    But keep in mind if you have sections in your document, it may causes problems (check this for more information : http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx)