我想加载一个XML
,并使其可用于所有事件。在下面的应用程序中,Button1
andButton3
事件使用load XML
,而Button2
不会,我不得不在事件中加载它。我假设每次加载文件时都会占用更多资源,而这是我想避免的。我的问题是:-我是否必须找到其他方法来填充Datagridview
?-XML
如果需要将文件加载到其他地方以节省系统资源,是否需要以某种方式卸载文件。
我是编程新手,自学成才,因此如果术语不正确,请提前道歉。
它是Windows形式的应用程序,具有:
XML如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<Config>
<Categories>
<Category Name="OneChar">
<Entry>
<Name>a</Name>
<id>1</id>
</Entry>
<Entry>
<Name>b</Name>
<id>2</id>
</Entry>
<Entry>
<Name>c</Name>
<id>3</id>
</Entry>
</Category>
<Category Name="TwoChar">
<Entry>
<Name>aa</Name>
<id>11</id>
</Entry>
<Entry>
<Name>bb</Name>
<id>22</id>
</Entry>
<Entry>
<Name>cc</Name>
<id>33</id>
</Entry>
</Category>
</Categories>
<Schemes>
</Schemes>
</Config>
代码如下:
using System;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
namespace List_box_multiple_query
{
public partial class Form1 : Form
{
XDocument xdoc = XDocument.Load("Config\\TestFile.xml");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
var result = xdoc.XPathSelectElements("/Config/Categories/Category [@Name='TwoChar']/Entry/Name");
foreach (string entry in result)
{
listBox1.Items.Add(entry);
}
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
XmlDocument doc = new XmlDocument();
doc.Load("Config\\testfile.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("/Config/Categories/Category[@Name='OneChar']/Entry");
foreach (XmlNode entry in nodeList)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = entry["Name"].InnerText.ToString();
dataGridView1.Rows[n].Cells[1].Value = entry["id"].InnerText.ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
var result = xdoc.XPathSelectElements("/Config/Categories/Category [@Name='TwoChar']/Entry/Name");
foreach (string entry in result)
{
comboBox1.Items.Add(entry);
}
}
}
}
首先,您需要始终使用XDocument或XmlDocument。
您可以定义一个
private Lazy<XmlDocument> docLazy =
new Lazy<XmlDocument>(() =>
{
XmlDocument doc = new XmlDocument();
doc.Load("Config\\TestFile.xml");
return doc;
}
);
然后在所有处理程序中使用它
var doc = docLazy.Value;
这样,仅在第一次调用时才从文件中加载它,然后将其缓存在内存中。
我先前的答案与之相似,但对于XDocument。
回复评论
有没有一种简单的方法可以选择XML中的节点并使用其内容...?
是的,例如
var test_nodeList = xdoc.Descendants("Category")
.Where(x => x.Attribute("Name").Value.Equals("OneChar"))
.Descendants("Entry");
代替
nodeList = root.SelectNodes("/Config/Categories/Category[@Name='OneChar']/Entry");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句