如何将文件夹中的所有Xml文件加载到XmlDocument

使用下面的代码,我可以在XmlDocument xWorkload中加载一个Xml文件。

XmlDocument xWorkload = new XmlDocument(); private void button1_Click(object sender, RoutedEventArgs e) { var outputxml = new StringBuilder(string.Empty); Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "demo"; // Default file name dlg.DefaultExt = ".xml"; // Default file extension dlg.Filter = "Xml documents (.xml)|*.xml"; // Filter files by extension var result = dlg.ShowDialog(); //Opens the dialog box if (result == true) { xWorkload.Load(dlg.FileName); string Path = dlg.FileName.Replace(dlg.SafeFileName, ""); } } 

假设,文件夹中有多个Xml文件,我想在xWorkload中加载所有Xml文件,并将这些xml文件存储在一个字符串中我该怎么做?这可以在wpf中使用XmlDocument来完成(不是LINQ)。 PLZ建议

您可以使用FolderBrowserDialog选择Xml Files根目录,然后:

 FolderBrowserDialog fd = new FolderBrowserDialog(); DialogResult result = fd.ShowDialog(); if(result == DialogResult.OK) { string[] files = Directory.GetFiles(fd.SelectedPath) .Where(p => p.EndsWith(".xml")) .ToArray(); foreach(var path in files) { XDocument xDoc = XDocument.Load(path); // read Xml file } }