问题描述
||
我正在尝试从SL 4富文本框的xaml内容中获取纯文本。
内容如下所示:
<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 : \"\";
}
}
段落为空。
我究竟做错了什么?
感谢您的任何提示...
解决方法
选择元素时,需要在XML中考虑名称空间,可以使用
XNamespace
进行声明和使用-这可以:
XNamespace xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\";
var Paras = root.Descendants(xmlns + \"Paragraph\");
, 感谢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();
}
有效!希望这对您有所帮助。
阮明贤