2011-05-29 114 views
1


我想從SL 4富文本框的xaml內容中獲取純文本。
內容如下:從Silverlight富文本框中提取純文本 - 從LINQ到XML

<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> 

當我試試這個:

  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"); 
        text += null != a ? (string) a : ""; 
       } 
      } 

帕拉斯是空的。
我在做什麼錯?
感謝您的任何提示...

回答

2

你需要考慮你的XML命名空間中選擇元素時,您可以使用XNamespace聲明和使用它 - 這個工程:

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

謝謝,那很簡單。 – Number8 2011-05-29 17:29:55

2

感謝BrokenGlass 。全功能:

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(); 
    } 

它的工作!希望這對你有所幫助。 Nguyen Minh Hien