开发者

Help me improve a OpenXML linq-to-xml query!

Guess people need some experience with Linq-to-xml and knowledge of the build of a openXML word document.

I have this L开发者_JAVA技巧inq to XML query that's supposed to find Content Controls. It works most of the time but I think it's still just juryrigged and not proper.

How it works, if I understand correctly, is that it checks StdRuns and finds if it's properties include one named Tag.

Problem is that Content Controls are perhaps not necceserily a part of a RUN. For example if it's added first in a line. I don't wan't to hit problems later on so I wonder if there is any better way of hitting all Content Controls using linq.

This is hwo the Linq query is now:

var cont = from sdt in document.MainDocumentPart.RootElement.Descendants<SdtRun>() 
                       let sdtPr = sdt.GetFirstChild<SdtProperties>()
                       let tag = (sdtPr == null ? null : sdtPr.GetFirstChild<Tag>())
                       where tag != null
                       select new
                       {
                           SdtProps = sdtPr,
                           TagName = tag.GetAttribute("val", sdt.NamespaceUri).Value
                       };

Thanks in advance.


Check out Eric White's blog. His whole site is really good to learn functional programming with the Open XML SDK. From his site:

private static void IterateContentControlsForPart(OpenXmlPart part)
{
    XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    XDocument doc = part.GetXDocument();
    foreach (var sdt in doc.Descendants(w + "sdt"))
    {
        Console.WriteLine("Found content control");
        Console.WriteLine("=====================");
        Console.WriteLine(sdt.ToString());
        Console.WriteLine();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜