简体   繁体   English

如何从文档中删除元素?

[英]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? 有没有办法迭代文档并删除所有<:p />元素,如果他们没有任何运行? 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. 这是我到目前为止所做的,但它只删除了空的<w:p />元素。

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

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 ) 但请记住,如果文档中有部分,则可能会导致问题(请查看此信息以获取更多信息: http//msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v = office) .14).aspx

I would load the xml into an XmlDocument and then use linq: 我会将xml加载到XmlDocument中,然后使用linq:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

var rootNode = doc.DocumentElement;

XmlNodeList ps = rootNode.SelectNodes("//p");
for (int i = 0; i < ps.Count; i++)
{
     if (ps[i].SelectNodes("//pr").Count == 0)
     {
         rootNode.RemoveChild(ps[i]);
     }
}

That code is completely untested though, but it does compile. 该代码完全未经测试,但它确实编译。 Let me know if this isn't any good for you and check out do some googling of Xml Parsing! 如果这对您没有任何好处,请告诉我,并查看一些Xml解析的谷歌搜索!

i'm using Linq, This can do better. 我正在使用Linq,这可以做得更好。

/*parent is the document body*/
parent.Descendants<Paragraph>().Where(p=>p.Descendants<Run>().Count()==0).All(p =>
{
   p.Remove();
   return true;
});

Hope this helps. 希望这可以帮助。 Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM