简体   繁体   中英

What is the best way to generate an id for new Xelement in Linq to XML?

I've been using guid's to identify elements in an xml document for editing. It seems that guid's are a lot more space than just an id field. In sql there is auto increment. Is there something similar or a decent way to auto increment for xml elements in Linq to XML?

The only constraint may be that once a number is used it cannot be used again.

Thanks.

I don't know what the "best" way is, but I'd think using a GUID would be a sure-fire way of getting a unique value for your ID field.

If you wanted an alternative method that uses a smaller number, you could try checking the file each time prior to inserting, and getting the next available ID that's one larger than the previous:

private int GenerateNextId()
{
   var file = XDocument.Load("yourFile.xml");  // or pass an XDocument in
                                               // so you don't have to reload it

   return file.Descendants("SomeElement")
              .OrderByDescending(x => Convert.ToInt32(x.Attribute("ElementId").Value))
              .Select(x => Convert.ToInt32(x.Attribute("ElementId").Value))
              .FirstOrDefault() + 1;
}

This is just posted as an alternative. I don't know how efficient this is as your XML grows in size. YMMV


If you decide to keep using the GUID, there are ways to shorten it, such as this SO post :

Convert.ToBase64String(Guid.NewGuid().ToByteArray());

I tried it out - the generated ID is nearly cut in half:

0b427c5a-1541-4cb4-8995-4e67dac61654
WnxCC0EVtEyJlU5n2sYWVA==

d1205a49-f64b-4418-8449-b1cd52f06624
SVog0Uv2GESESbHNUvBmJA==

I agree with @GrantWinney that GUIDs are a surefire way to get unique IDs.

However, you can also use DateTime.Now.ToFileTimeUtc(); . It's not not guaranteed to be unique, though, like GUIDs: eg computers in different timezones adding XML records using this method, or even different computers in the same office.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM