从XML读取元素并在方法中使用它们

时间:2012-01-25 18:09:21

标签: c# xml list

我有以下代码检查是否创建了一些文件夹;具有完整路径的文件夹列表存储在xml文件中。

namespace InstallationCheck
{
    public class Checking
    {
       public bool result()
        {

            bool returns = true;

         //Reads from xml file the element content from a tag line (ex: esecpath)
            string esecpath = Checking.CitXml("C:\\testconfig.xml", "esecpath");
            string agentpath = Checking.CitXml("C:\\testconfig.xml", "agentpath");
            string datapath = Checking.CitXml("C:\\testconfig.xml", "datapath");
            string debugpath = Checking.CitXml("C:\\testconfig.xml", "debugpath");
            string helppath = Checking.CitXml("C:\\testconfig.xml", "helppath");
            string patchpath = Checking.CitXml("C:\\testconfig.xml", "patchpath");

            // Compare the paths from XML with the paths of the app.
            List<bool> listtest = new List<bool>();
            listtest.Add((Directory.Exists(esecpath) == true));
            listtest.Add((Directory.Exists(agentpath) == true));
            listtest.Add((Directory.Exists(datapath) == true));
            listtest.Add((Directory.Exists(debugpath) == true));
            listtest.Add((Directory.Exists(patchpath) == true));
            listtest.Add((Directory.Exists(helppath) == true));

            //Cheking if any of paths are false
            foreach (bool varia in listtest)
            {
                returns = returns && varia;
            }
            return returns;  
        }

            // Reading from XML method
        public static string CitXml(string xmlpath, string field)
        {
            XmlTextReader xmlReader = new XmlTextReader(xmlpath);
            xmlReader.WhitespaceHandling = WhitespaceHandling.None;

            xmlReader.ReadToDescendant(field);
            return xmlReader.ReadElementString(field);

        }


    }

}

现在我需要检查是否创建了一些文件(其中很多),以免我手动添加所有代码,我想知道该怎么做;我希望代码读取xml文件并检查是否已创建所有文件(来自xml)。所以我想知道你们中的某个人是否可以提供一个ideea,一个暗示(所以我可以去阅读它),也许是一个代码示例。谢谢。

1 个答案:

答案 0 :(得分:0)

好吧,看看是否有任何创建,重新编写代码如下:

public bool result()
{    
    Dictionary<string, string> files = new Dictionary<string, string>();
    files.Add("esecpath", "C:\\testconfig.xml");
    // ... etc for each file

    // if you want to see if any don't exist, then use ...
    // if(files.Any(f => !File.Exists(f.Value)))

    // else, these are all the created files
    var createdFiles = files.Where(f => !File.Exists(f.Value));
    if(createdFiles.Count() > 0)
    {
        // A file doesn't exist!  Therefore you are creating it!
    }
    var directories = files.Select(f => Checking.CitXml(f.Value, f.Key));

    return directories.All(d => Directory.Exists(d));
}