using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml.Linq;
using System.Windows.Browser;
namespace XmlViewer
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
if (HtmlPage.IsEnabled)
HtmlPage.RegisterScriptableObject("XmlViewer", this);
//SetXml("Books.xml");
}
private void setXmlString(string xmlString)
{
XDocument xd = XDocument.Parse(xmlString);
tvXml.Items.Clear();
tvXml.Items.Add(exploreXElement(xd.Root));
}
[ScriptableMember]
public void SetXml(string xml)
{
try
{
if (xml.StartsWith("<")) setXmlString(xml);
else
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null)
MessageBox.Show("Invalid XML in " + xml);
else
setXmlString(e.Result);
};
wc.DownloadStringAsync(new Uri(xml, UriKind.Relative));
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid XML content or source!\n" +
ex.Message);
return;
}
}
#region TreeView Helper
SolidColorBrush cPurple = new SolidColorBrush(Colors.Purple);
SolidColorBrush cBlue = new SolidColorBrush(Colors.Blue);
SolidColorBrush cGreen = new SolidColorBrush(Colors.Green);
SolidColorBrush cOrange = new SolidColorBrush(Colors.Orange);
SolidColorBrush cBlack = new SolidColorBrush(Colors.Black);
//Generate name textblock(fixed width) and value textblock for
//XElement or XAttribute
private Grid genHeader(object obj)
{
string n = "", v = "", tp = "";
SolidColorBrush c = cBlack;
if (obj is XElement)
{
var xe = obj as XElement;
n = xe.Name.LocalName;
v = xe.HasElements ? "" : xe.Value;
//Remove line-break
v = v.Replace("\r", "").Replace("\n", "");
while (v.Contains(" "))
v = v.Replace(" ", " ");
tp = xe.ToString();
c = xe.HasElements ? cBlue : cGreen;
}
else if (obj is XAttribute)
{
var xa = obj as XAttribute;
n = "[" + xa.Name.LocalName + "]";
v = xa.Value;
tp = "Attribute=" + v;
c = cPurple;
}
Grid g = new Grid();
g.ColumnDefinitions.Add(new ColumnDefinition() {
Width = new GridLength(100) });
g.ColumnDefinitions.Add(new ColumnDefinition() {
Width = GridLength.Auto });
TextBlock tbName = new TextBlock() { Text = n, Foreground = c };
if (tp.Length > 0) ToolTipService.SetToolTip(tbName, tp);
g.Children.Add(tbName);
g.Children.Add(new TextBlock() { Text = v, });
Grid.SetColumn(g.Children[1] as TextBlock, 1);
return g;
}
//Use recursive to build TreeView nodes
private TreeViewItem exploreXElement(XElement xe)
{
TreeViewItem tvi = new TreeViewItem();
tvi.Header = genHeader(xe);
tvi.Tag = xe;
foreach (var at in xe.Attributes())
tvi.Items.Add(new TreeViewItem() {
Header = genHeader(at), Tag = at });
foreach (var ch in xe.Elements())
tvi.Items.Add(exploreXElement(ch));
return tvi;
}
#endregion
}
}