开发者

Extract plain text from silverlight rich text box - LINQ to XML

I am trying to get the plain text from the xaml content of the SL 4 rich text box.

The content looks like this:

<Section xml:space=\"preserve\" HasTrailingParagraphBreakOnPaste=\"False\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">
    <Paragraph FontSize=\"12\" FontFamily=\"Arial\" Foreground=\"#FF000000\" FontWeight=\"Normal\" FontStyle=\"Normal\" FontStretch=\"Normal\" TextAlignment=\"Left\">
         <Run Text=\"Biggy\" />
    </Paragraph>
</Section>

When I try this:

            XElement root = XElement.Parse(xml);
            var Paras = root.Descendants("Paragraph");
            foreach (XElement para in Paras)
            {
                foreach (XElement run in Paras.Descendants("Run"))
                {
                    XAttribute a = run.Attribute("Text");
                    t开发者_如何学运维ext += null != a ? (string) a : "";
                }
            }

Paras is empty.

What am I doing wrong?

Thanks for any hints...


You need to account for the namespace in your XML when selecting elements, you can use XNamespace to declare and use it - this works:

XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
var Paras = root.Descendants(xmlns + "Paragraph");


Thanks to BrokenGlass.The full function:

string StringFromRichTextBox(string XAML)
    {
        XElement root = XElement.Parse(XAML);
        XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
        StringBuilder sb = new StringBuilder();
        var Paras = root.Descendants(xmlns + "Paragraph");            
        foreach (XElement para in Paras)
        {
            foreach (XElement run in Paras.Descendants(xmlns + "Run"))
            {
                XAttribute a = run.Attribute("Text");
                sb.Append(null != a ? (string)a : "");
            }
        }
        return sb.ToString();
    }

It worked! Hope this help you. Nguyen Minh Hien

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜