How to load all Xml files from a folder in an XmlDocument

With my code below, I can load one Xml file into XmlDocument xWorkload.

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, "");
            }
        }

Suppose that there is more than one Xml file in a folder, and I want to load all the Xml files into xWorkload and store these XML files in a line. How to do this? This can be done in wpf using only XmlDocument (Not Linq). Plz suggest

+4
source share
1 answer

You can use FolderBrowserDialogXml Files to select the root directory, and then:

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
    }
}
+6
source

Source: https://habr.com/ru/post/1524222/


All Articles