MyDataGridView系結到DataSource此處定義的:
BindingList<CompanyProfile> DataSource = new BindingList<CompanyProfile>();
CompanyProfile類是:
public class CompanyProfile
{
public string CompanyName { get; set; }
public string SiteName { get; set; }
public string IMO { get; set; } = "Some Value";
}
現在我想獲取整個 DataSource 并撰寫一個包含所有專案的 XML 檔案。之前,我試過這個序列化:
// Iterate the datasource list, not the DataGridView.
foreach (CompanyProfile companyProfile in DataSource)
{
CreateClientFile(
companyProfile,
fileName: Path.Combine(appData,
$"{companyProfile.CompanyName}_{companyProfile.SiteName}.xml")
);
}
CreateClientFile使用 XmlSerializer的地方:
private void CreateClientFile(CompanyProfile companyProfile, string fileName)
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(CompanyProfile));
using (var writer = new StreamWriter(fileName))
{
x.Serialize(writer, companyProfile);
}
// Open the file to view the result
Process.Start("notepad.exe", fileName);
}
但我最終為每條記錄創建了一個檔案。如何序列化我的 DataSource 以便它生成一個包含所有CompanyProfile 記錄的檔案?
我真的很想學習和掌握這個概念,按照建議開始閱讀有關序列化和資料系結的內容,但我被卡住了。
我希望有人愿意進一步幫助我
uj5u.com熱心網友回復:
這將詳述jdweng的出色評論。
在您發布的代碼中,您瀏覽DataSource并使用XmlSerializer每條記錄。但是,要實作您想要的結果,即DataSource寫入單個檔案并擁有所有記錄,您需要更改序列化程式的定義:
XmlSerializer x = new XmlSerializer(
typeof(BindingList<CompanyProfile>),
new XmlRootAttribute("root"));
另一個更改很簡單,因為您采用您的btnSerialize_Click方法并使用該行序列化整個 Listx.Serialize(writer, DataSource)。
private void btnSerialize_Click(object sender, EventArgs e)
{
var fileName = Path.Combine(
appData,
"CompanyProfiles.xml");
using (var writer = new StreamWriter(fileName))
{
x.Serialize(writer, DataSource);
}
Process.Start("notepad.exe", fileName);
}
您的檔案現在具有正確的檔案結構,因為有一個root節點。兩條CompanyProfile記錄的資料位于root節點下:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyProfile>
<CompanyName>Linear Technology</CompanyName>
<SiteName>Colorado Design Center</SiteName>
<IMO>Some Value</IMO>
</CompanyProfile>
<CompanyProfile>
<CompanyName>Analog Devices</CompanyName>
<SiteName>1-1-2</SiteName>
<IMO>Some Value</IMO>
</CompanyProfile>
</root>
我希望這將有助于您了解更多關于序列化的目標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489244.html
