class Mapper
{
private string sourceXmlFile;
private XDocument xmlData;
public Mapper(string xmlFilePath)
{
sourceXmlFile = xmlFilePath;
}
private void BuildNodes(TreeViewItem treeNode, XElement element)
{
string attributes = "";
if (element.HasAttributes)
{
foreach (var att in element.Attributes())
{
attributes += " " + att.Name + " = " + att.Value;
}
}
TreeViewItem childTreeNode = new TreeViewItem
{
Header = element.Name.LocalName + attributes,
IsExpanded = true
};
if (element.HasElements)
{
foreach (XElement childElement in element.Elements())
{
BuildNodes(childTreeNode, childElement);
}
}
else
{
TreeViewItem childTreeNodeText = new TreeViewItem
{
Header = element.Value,
IsExpanded = true
};
childTreeNode.Items.Add(childTreeNodeText);
}
treeNode.Items.Add(childTreeNode);
}
public void LoadXml(TreeView treeview)
{
try
{
if (sourceXmlFile != null)
{
xmlData = XDocument.Load(sourceXmlFile, LoadOptions.None);
if (xmlData == null)
{
throw new XmlException("Cannot load Xml document from file : " + sourceXmlFile);
}
else
{
TreeViewItem treeNode = new TreeViewItem
{
Header = sourceXmlFile,
IsExpanded = true
};
BuildNodes(treeNode, xmlData.Root);
treeview.Items.Add(treeNode);
}
}
else
{
throw new IOException("Xml file is not set correctly.");
}
}
catch (IOException ioex)
{
//log
}
catch (XmlException xmlex)
{
//log
}
catch (Exception ex)
{
//log
}
}
}
這是每一個XML結構最通用的版本。例如:
<Catalog>
<Book id="bk101">
<Author>Garcia, Debra</Author>
<Title id="33">XML Developer's Guide</Title>
<Genre>Computer</Genre>
<Price>44.95</Price>
<PublishDate>2000-10-01</PublishDate>
<Description>An in-depth look at creating applications
with XML.</Description>
</Book>
<Book id="bk102">
<Author>Garcia, Debra</Author>
<Title>Midnight Rain</Title>
<Genre>Fantasy</Genre>
<Price>5.95</Price>
<PublishDate>2000-12-16</PublishDate>
<Description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</Description>
</Book>
</Catalog>
會產生這樣的:
所有這些解決方案爲你工作? – 2010-02-25 20:10:00
問題是「如何從XML文件創建樹視圖」不是手動嵌套在xaml中 – 2016-09-11 03:45:02