C#读取Xml配置文件

时间:2017-11-18 13:57:39

标签: c# xml io config

我有一个包含truefalse语句的Xml配置文件。我需要一个function,它会返回bool值。

<Configs>
     <steerWithMouse>true</steerWithMouse>
     <debug>false</debug>
</Configs>

该函数需要一个string值才能继续使用该节点。所以像这样:

bool steerWithMouse = ReadConfigs("SteerWithMouse");

bool debug = ReadConfigs("debug");

public bool ReadConfigs(string config) {

        try {
            //Where the code should go.

        }
        catch {
            //If the program fails to find or load the file correctly.

            ModConsole.Error("Falied to load configs file."); //The console.
            steerWithMouse = true;
            debug = false;
        }
    }

由于我对Xml文件缺乏经验,我只是在尝试这样做时遇到了挫败感。它要么没有说什么,要么没有编译或返回整个文档。我很乐意接受这方面的帮助。

1 个答案:

答案 0 :(得分:0)

public bool ReadConfigs(string config) {

        string statement = null;

        try {
            string xmlFile = File.ReadAllText(ModLoader.GetModConfigFolder(this) + "\\configs.xml");
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xmlFile);
            XmlNodeList nodeList = xmldoc.GetElementsByTagName(config);
            string Short_Fall = string.Empty;
            foreach (XmlNode node in nodeList) {
                statement = node.InnerText;

            }
        }
        catch {
            ModConsole.Error("Falied to load configs file!");
            statement = null;
        }

        try {

            if (statement != null) {
                return bool.Parse(statement);
            }
            else
                return false;
        }
        catch {
            ModConsole.Error("Invalid syntax in configs!");
            return false;
        }
    }

This复制粘贴似乎解决了它。