如何从WPF中的XML文件将char转换为XElement.value ?我打印了树元素,但没有打印它们的值;我得到的无法从'char'转换为'System.Xml.Linq.XElement'参数。 Perphaps我正在迭代错误的类型?
谢谢
public partial class MainWindow : Window
{
string file1 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.strings.xsd");
string file2 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.bg.strings.xml");
string file3 = System.IO.File.ReadAllText(@"H:\MpxWpfComponents.fr.strings.xml");
public MainWindow()
{
InitializeComponent();
}
private void btnOpenFile_Click1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
listXML.Items.Add(Path.GetFileName(filename));
}
var xmlDoc = XDocument.Parse(file2);
BuildTree(treeView.Items, xmlDoc.Elements().First());
}
private void BuildTree(ItemCollection itemCollection, XElement xElement)
{
var item = new TreeViewItem() { Header = xElement.Name.LocalName };
itemCollection.Add(item);
foreach (var xElem in xElement.Elements())
{
BuildTree(item.Items, xElem);
}
item = new TreeViewItem() { Header = xElement.Value };
itemCollection.Add(item);
foreach (var xElem in xElement.Value)
{
BuildTree(item.Items, xElem);
}
}
答案 0 :(得分:1)
Value
属性返回元素的文本内容。您想迭代元素的子元素:
private void BuildTree(ItemCollection itemCollection, XElement xElement)
{
var item = new TreeViewItem() { Header = xElement.Name.LocalName };
itemCollection.Add(item);
foreach (var xElem in xElement.Elements())
{
BuildTree(item.Items, xElem);
}
item = new TreeViewItem() { Header = xElement.Value };
itemCollection.Add(item);
foreach (var xElem in xElement.Elements()) //<---
{
BuildTree(item.Items, xElem);
}
}