/// <summary>
/// Traverses the XElement and adds text to the InlineCollection.
/// </summary>
/// <param name="element"></param>
/// <param name="inlines"></param>
private static void ParseText(XElement element, InlineCollection inlines)
{
if (element == null) return;
InlineCollection currentInlines = inlines;
var elementName = element.Name.ToString().ToUpper();
switch (elementName)
{
case ElementA:
var link = new Hyperlink();
var href = element.Attribute("href");
if(href != null)
{
try
{
link.NavigateUri = new Uri(href.Value);
}
catch (System.FormatException) { /* href is not valid */ }
}
inlines.Add(link);
currentInlines = link.Inlines;
break;
case ElementB:
case ElementStrong:
var bold = new Bold();
inlines.Add(bold);
currentInlines = bold.Inlines;
break;
case ElementI:
case ElementEm:
var italic = new Italic();
inlines.Add(italic);
currentInlines = italic.Inlines;
break;
case ElementU:
var underline = new Underline();
inlines.Add(underline);
currentInlines = underline.Inlines;
break;
case ElementBr:
inlines.Add(new LineBreak());
break;
case ElementP:
// Add two line breaks, one for the current text and the second for the gap.
if (AddLineBreakIfNeeded(inlines))
{
inlines.Add(new LineBreak());
}
Span paragraphSpan = new Span();
inlines.Add(paragraphSpan);
currentInlines = paragraphSpan.Inlines;
break;
case ElementLi:
inlines.Add(new LineBreak());
inlines.Add(new Run { Text = " • " });
break;
case ElementUl:
case ElementDiv:
AddLineBreakIfNeeded(inlines);
Span divSpan = new Span();
inlines.Add(divSpan);
currentInlines = divSpan.Inlines;
break;
}
foreach (var node in element.Nodes())
{
XText textElement = node as XText;
if (textElement != null)
{
currentInlines.Add(new Run { Text = textElement.Value });
}
else
{
ParseText(node as XElement, currentInlines);
}
}
// Add newlines for paragraph tags
if (elementName == ElementP)
{
currentInlines.Add(new LineBreak());
}
}