[我正在尝试编写一种方法来从Northwind数据库中获取类别及其各自的产品,然后使用xml序列化来写入文件。
我已经尝试了以下代码,但在标题中得到了详细的错误。 (已创建文件,但未写入任何XML)。
有人能够告知我的代码有什么问题吗?任何帮助将不胜感激。谢谢。
static async void SerializeCategoriesWithXML() {
FileStream xmlFileStream = null;
XmlWriter xml = null;
// Create file to write to :
string path = Combine(CurrentDirectory, "CategoriesAndTheirProducts.xml");
// Create a file stream :
xmlFileStream = File.Create(path);
// Wrap the file stream in an Xml writer helper and automatically indent the nested elements :
xml = XmlWriter.Create(xmlFileStream, new XmlWriterSettings { Indent = true });
using (var db = new NorthwindContext())
{
// A query to get all categories and their related products :
IQueryable<Categories> cats = db.Categories
.Include(c => c.Products
.ToList());
await using (FileStream stream = File.Create(path))
{
// Write the Xml declaration :
xml.WriteStartDocument();
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach(Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();
xml.Flush();
}
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();
}
}
}
共享代码存在多个问题。
让我们尝试理解每个问题,并考虑可能的解决方案-据我了解,问题陈述是,您想创建一个XML文件,其中包含类别和产品。因此,为简单起见,我假设您正在尝试获取如下所示的XML文件-
<?xml version="1.0" encoding="utf-8"?>
<categories>
<category>
<product>Chai</product>
<product>Chang</product>
<product>Guaraná Fantástica</product>
<product>Sasquatch Ale</product>
<product>Steeleye Stout</product>
<product>Côte de Blaye</product>
</category>
<category>
<product>Aniseed Syrup</product>
<product>Chef Anton's Cajun Seasoning</product>
<product>Chef Anton's Gumbo Mix</product>
<product>Grandma's Boysenberry Spread</product>
</category>
</categories>
上述发布的代码出了什么问题-问题1:使用指定路径多次创建文件-
// Create a file stream :
xmlFileStream = File.Create(path);
您已经触发了上一行中的File.Create,因此,当您触发以下代码时,它会说文件已在使用中 ....(不需要以下行)
await using (FileStream stream = File.Create(path))
问题2:Linq查询不正确。您可以使用以下代码替换linq查询-
var cats = db.Categories
.Include(c => c.Products).ToList();
问题3:Xml构造错误...您需要将类别标签包装在父级中,因为将创建多个类别对象。同样,在上面的代码中,您尝试在读取一个类别时刷新xml。最后一次需要刷新一次
xml.WriteEndElement();
已执行。
因此您可以如下替换用于创建xml的代码块-
// Write the Xml declaration :
xml.WriteStartDocument();
xml.WriteStartElement("categories");
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach (Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.Flush();
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();
现在,该文件应使用category-> category []创建。以及每个类别->产品[]。
谢谢