![](/img/trans.png)
[英]How to Load Xml file whilelocking it using XDocument.Load() method?
[英]Xml file not available to all event methods using XDocument.Load in C#
我想加載XML
並使其可用於所有事件。 在下面的應用程序中, Button1
和Button3
事件使用加載的XML
,而Button2
則不會,我不得不在事件內加載它。 我假設每次加載文件都會占用更多資源,而我試圖避免這種情況。 我的問題是:-我是否必須找到其他方法來填充Datagridview
? -如果需要將XML
文件加載到其他地方以節省系統資源,是否需要以某種方式卸載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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.