加载XML文件到系统中

Posted 我心永恒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了加载XML文件到系统中相关的知识,希望对你有一定的参考价值。

using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Collections.Generic;

namespace XMLFileLoad.Common
{
public class StepRuleSetting
{
private const string SettingsPath = "StepRule.xml";
private static StepRuleSetting _instance;
private readonly DataTable StepRuleDT = new DataTable();
private readonly Dictionary<string,List<string>> DicRules = new Dictionary<string,List<string>>();
private List<string> Rules = new List<string>();
private StepRuleSetting()
{
}

public static StepRuleSetting Instance
{
get
{
if (_instance == null) _instance = new StepRuleSetting();
_instance.Load();
return _instance;
}
}

public bool HasContainsKey(string stepType)
{
return DicRules.ContainsKey(stepType);
}
public List<string> GetStepRules(string stepType)
{
if (HasContainsKey(stepType))
{
Rules = DicRules[stepType];
if (Rules.Count <= 0)
{
MessageWindow.Show(MessageLevel.Warning, "No rules under this steptype: " + SettingsPath);
}
}
return Rules;
}

private void Load()
{
var xml = new XmlDocument();
try
{
xml.Load(Path.Combine(Environment.CurrentDirectory, "Settings", SettingsPath));

var ruleListRoot = xml.DocumentElement.SelectSingleNode("/RuleList");

if (ruleListRoot == null)
{
return;
}

var stepTypeLists = xml.DocumentElement.SelectNodes("/RuleList/StepType");
foreach (XmlNode node in stepTypeLists)
{
if (node.Attributes["name"] == null)
{
throw new ArgumentException("Required attribute ‘name‘ is missing in configuration file " +
SettingsPath);
}
}
foreach (XmlNode node in stepTypeLists)
{
var stepRuleLists = node.ChildNodes;
List<string> rules = new List<string>();
foreach (XmlNode rule in stepRuleLists)
{
if (rule.Name == "Rule")
{
rules.Add(rule.InnerText);
}
}
if (!DicRules.ContainsKey(node.Attributes["name"].Value))
{
DicRules.Add(node.Attributes["name"].Value, rules);
}
}


}
catch (ArgumentException ex)
{
// Ignore the duplicate key.
MessageWindow.Show(MessageLevel.Warning, "There is configuration error in config file: " + SettingsPath);
}
catch (Exception ex)
{
var errMsg = string.Format("Errors occured while reading TreeNode setting from file [{0}].",
SettingsPath);
// Color list configuration failure does not affect functionality. Just show warnings.

// TODO: do localization for this message.
MessageWindow.Show(MessageLevel.Warning, "There is configuration error in config file: " + SettingsPath);

//Insert Exeption log
}
finally
{
xml = null;
}
}
}
}

以上是关于加载XML文件到系统中的主要内容,如果未能解决你的问题,请参考以下文章

SSIS - 移动并打开 zip 文件/加载 xml 文件到 BD

将外部文件中的值加载到 pom.xml

如何将xml加载到plist

在运行时将 xml 配置文件动态加载到 Flex4/Flash 电影中的最佳方法?

如何使用 Javascript 加载 XML 文件内容?

Android-View的创建从xml到View