C# 读取资源文件.resx 中的xml资源

时间:2022-07-01 15:50:49

主要是以字符串的形式来读取xml,然后通过遍历读取节点,通过节点属性名称获取属性值

/// <summary>
/// 初始化OPC参数配置
/// </summary>
/// <returns></returns>
public static OCPParamsDefine InitOPCParamsConfig()
{
OCPParamsDefine _OCPParamsDefine = null; ;
byte[] buffer = Encoding.GetEncoding("GB2312").GetBytes(OPCClientResource.OPCClientParams);
MemoryStream ms = new MemoryStream();
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
XmlTextReader xmlReader = new XmlTextReader(ms);
_OCPParamsDefine= LoadFromXml(xmlReader);
xmlReader.Close();
return _OCPParamsDefine;

}

/// <summary>
/// 从xml文件加载配置
/// </summary>
/// <param name="xmlReader">xml文档</param>
static OCPParamsDefine LoadFromXml(XmlTextReader xmlReader)
{
xmlReader.WhitespaceHandling = WhitespaceHandling.None;
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && string.Compare(xmlReader.Name, "OPCServerParam", true) == 0)
{
OCPParamsDefine _OCPParamsDefine = new OCPParamsDefine();
if (!xmlReader.IsEmptyElement)
{
xmlReader.Read();
int beginNodeDepth = xmlReader.Depth;
do
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (string.Compare(xmlReader.Name, "Groups", true) == 0)
{
string groupsName=xmlReader.GetAttribute("Name");
_OCPParamsDefine.GroupsName = groupsName;
// OCPParamsDefine _OCPParamsDefine = new OCPParamsDefine(groupsName);
do
{
xmlReader.Read();
if (xmlReader.NodeType == XmlNodeType.Element)
{
if ((string.Compare(xmlReader.Name, "Group", true) == 0))
{
do
{
string groupName=xmlReader.GetAttribute("Name");
Group group = new Group(groupName) { GroupsName=groupsName};
group.Items = GetItems(xmlReader, groupName, groupsName);//获取组下的每一项

_OCPParamsDefine.Groups.Add(group);
xmlReader.Skip();
} while (!xmlReader.EOF);
}
}
// xmlReader.Skip();
} while (!xmlReader.EOF);

}
}
// xmlReader.Skip();
} while (beginNodeDepth == xmlReader.Depth && !xmlReader.EOF);
}
return _OCPParamsDefine;
// break;
}
}
return null;
}

static List<Item> GetItems(XmlTextReader xmlReader, string groupName, string groupsName)
{
List<Item> items = new List<Item>();
xmlReader.Read();
if (xmlReader.NodeType == XmlNodeType.Element)
{
if ((string.Compare(xmlReader.Name, "Items", true) == 0))
{
do
{
xmlReader.Read();
if (xmlReader.NodeType == XmlNodeType.Element)
{
if ((string.Compare(xmlReader.Name, "Item", true) == 0))
{
string itemName = xmlReader.GetAttribute("Name");
int clientHandler = Convert.ToInt32(xmlReader.GetAttribute("ClientHandler"));
Item item = new Item() { GroupsName=groupsName,GroupName = groupName, _Item = itemName, ClientHandler = clientHandler };
items.Add(item);
// group.Items.Add(item);
}
}
// xmlReader.Skip();
} while (!xmlReader.EOF);
}
}
return items;
}