【发布时间】:2011-05-25 02:26:24
【问题描述】:
我正在开发 windows phone 7 应用程序。我使用 XML 作为我的应用程序的数据库。我正在为我的应用程序使用 XML 文件而不是数据库表。我的 xml 文件之一具有以下结构。
<?xml version="1.0" encoding="utf-8" ?>
<Categories>
<Category>
<Category_ID></Category_ID>
<Category_Name></Category_Name>
<TransactionType_ID></TransactionType_ID>
</Category>
<Category>
<Category_ID></Category_ID>
<Category_Name></Category_Name>
<TransactionType_ID></TransactionType_ID>
</Category>
</Categories>
在上面的 XML 文件中,我使用 LINQ to XML 通过我的移动应用程序的用户界面插入 Category_Name 和 TransactionType_ID 的值。在上面的 XML 文件中,我将 Category_ID 视为主键,将 TransactionType_ID 视为属于其他 xml 文件的外键。在上面的 XML 文件中,我想为节点 Category_ID 生成自动增量 ID,就像我们在数据库表中所做的那样。为此,我使用以下代码
private int new_record_id()
{
IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("Categories.xml", System.IO.FileMode.Open, isstore);
XDocument xmldetails = XDocument.Load(bookfile);
var details = (from detail in xmldetails.Descendants("Category")
select (int.Parse(detail.Element("Category_ID").Value))).Max();
bookfile.Close();
return details + 1;
}
但是当我在 XML 文件中插入第一条记录时,它会在下面的句子中出现错误,因为我的 XML 文件中开头没有记录。
var details = (from detail in xmldetails.Descendants("Category")
select (int.Parse(detail.Element("Category_ID").Value))).Max();
您能否提供我可以在 XML 文件中插入第一条记录的任何代码或链接或任何解决方案?如果我做错了什么,请指导我。
【问题讨论】:
标签: c# silverlight windows-phone-7 linq-to-xml auto-increment