【问题标题】:How to write ID in XML file for the first record by using LINQ to XML?如何使用 LINQ to XML 在 XML 文件中为第一条记录写入 ID?
【发布时间】: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


    【解决方案1】:

    好吧,首先你的查询可以更简单地写成:

    var id = xmlDetails.Descendants("book")
                       .Max(x => (int) x.Element("id"));
    

    现在,如果您希望能够处理 XML 中没有 书籍的情况,我会先明确测试:

    int id;
    if (xmlDetails.Descendants("book").Any())
    {
        id = xmlDetails.Descendants("book")
                       .Max(x => (int) x.Element("id"));
    }
    else
    {
        id = -1; // Or whatever you want to do
    }
    

    (如果您愿意,也可以使用条件运算符。)

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多