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

我是研究僧i 提交于 2019-12-06 05:13:37

问题


With my below code, I am able to load one Xml file in 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, there are more than one Xml files in a folder,And I want to load all the Xml files in xWorkload, and store those xml files in a string How shall I do it ?Can this be done in wpf using XmlDocument only(Not Linq). plz suggest


回答1:


You can use FolderBrowserDialog to select Xml Files root Directory, 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
    }
}


来源:https://stackoverflow.com/questions/21423183/how-to-load-all-the-xml-files-from-a-folder-to-an-xmldocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!