开发者

How to write ID in XML file for the first record by using LINQ to XML?

I am developing window phone 7 application. I am using XML as a database for my application. I am using a XML file instead of a database table for my application. I having the following structure for one of my xml file.

<?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>

In the above XML file I am inserting the values for Category_Name & TransactionType_ID through the user interface of my mobile application by using LINQ to XML. In the above XML file I am treating the Category_ID as a primary key & TransactionType_ID as a foreign key which belongs to other xml file. In the above XML file I want to generate the autoincrement id for the node Category_ID as we do in the database table. For this purpose I am using the following code

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;
        }

But when I insert first record in the XML file then it gives error in the following sentence because there is no record in my XML file at the beginning.

 var details = (from detail in xmldetails.Descendants("Category")
                               select (int.Parse(detail.Element("Category_ID").Value))).Max();

Can you please provide me any code or link or any solution t开发者_如何学运维hrough which I can insert the first record in the XML file ? If I am doing anything wrong then please guide me.


Well, to start with your query can be written much more simply as:

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

Now, if you want to be able to handle the case where there are no books in your XML, I'd test that explicitly first:

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
}

(You could use the conditional operator for this if you wanted, too.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜