C# 通过字符串找对应名称的变量、Winform跨容器调用变量、递归遍历XML
通过字符串,找对应名称的变量
ExceptionRecord er = new ExceptionRecord();//新建类的对象(变量在这个类中)
var fieldInfo = er.GetType().GetField("Params");//对应变量名的字符串
Dictionary<string, Dictionary<string, string>> tempDic = fieldInfo.GetValue(er) as Dictionary<string, Dictionary<string, string>>;
Winform跨容器调用变量
- 将designer中的private改为public
- 假设有A Form 和 B Panel, B想调用A中的变量。
- 首先在B 中创建A的对象 public A a,但是不实例化
- 然后去A 控件中的构造方法中实例化a对象
- public B b = new B()
- b.a = this
- 注意,实例化要在调用之前才可以。
递归遍历XML节点
思路:根据父节点_子节点或者祖父节点_父节点_子节点(因为节点下有名称向同的节点,便于区分,所以采用这种查找方式)名称去xml下逐个查找,如果是的话就访问这个节点,否则就继续找,
public void loadNode(XmlNode visitNode, Dictionary<string, Dictionary<string, string>> needs, List<XmlNode> record, XmlDocument xmlDoc)
{
//访问XML中的节点,如果是需要显示的节点,就显示到UI界面
if ((visitNode.ParentNode != null && needs.Keys.Contains(visitNode.ParentNode.Name + "_" + visitNode.Name))|| (visitNode.ParentNode.ParentNode != null && needs.Keys.Contains(visitNode.ParentNode.ParentNode.Name + "_"+visitNode.ParentNode.Name + "_" + visitNode.Name)))
{
foreach (XmlAttribute atb in visitNode.Attributes)
{
//Console.WriteLine("属性值" + atb.Name);
DataRow dr = dt.NewRow();
dr[0] = atb.Name;
Dictionary<string, string> tempDic;
if (needs.Keys.Contains(visitNode.ParentNode.Name + "_" + visitNode.Name))
{
tempDic = needs[visitNode.ParentNode.Name + "_" + visitNode.Name];
}
else
{
tempDic = needs[visitNode.ParentNode.ParentNode.Name + "_" + visitNode.ParentNode.Name + "_" + visitNode.Name];
}
try
{
string[] tempParam = new string[3];
tempParam[0] = dr[0].ToString();
//Console.WriteLine(tempDic.Keys.Count);
if (tempDic.Keys.Contains(atb.Name))
{
dr[1] = tempDic[atb.Name];
tempParam[1] = dr[0].ToString();
}
else
{
dr[1] = " ";
tempParam[1] = dr[0].ToString();
}
dr[2] = atb.Value;
tempParam[2] = dr[2].ToString();
dt.Rows.Add(dr);
exceptionRecords.Add(tempParam);
}
catch
{
}
}
}
}
public void recursionVisit(XmlDocument xmlDoc, XmlElement Node, Dictionary<string, Dictionary<string, string>> needs, List<XmlNode> record)
{
//递归访问节点
foreach (XmlElement visitNode in Node.ChildNodes)
{
loadNode(visitNode, needs, record, xmlDoc);
//Console.WriteLine("正在访问"+ visitNode.ToString());
recursionVisit(xmlDoc, visitNode, needs, record);
}
}
public void getXmlAttributesPlus(Dictionary<string, Dictionary<string, string>> needs, Dictionary<string, string> xmlPaths)
{
//遍历节点,直到走到最深,如果最深层不是所需要的节点就删除,否则就访问完删除然后回退一个
exceptionRecords = new List<string[]>();
foreach (KeyValuePair<string, string> xmlPath in xmlPaths)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath.Key);
XmlNodeList nodes = xmlDoc.SelectNodes(xmlPath.Value);
foreach (XmlElement node in nodes)
{
XmlElement visitNode = node;
List<XmlNode> record = new List<XmlNode>();//记录当前文件下已被访问的结点
recursionVisit(xmlDoc, visitNode, needs, record);
}
}
}