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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21423183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:39:02  来源:igfitidea点击:

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

c#xmlwpfxmldocument

提问by user42067

With my below code, I am able to load one Xml file in XmlDocument xWorkload.

使用下面的代码,我可以在 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, "");
            }
        }

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

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

回答by Selman Gen?

You can use FolderBrowserDialogto select Xml Files root Directory, then:

您可以使用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
    }
}