Granted, it's not Linq2XML but Linq is Linq and to query (bags) and then
update an object in (bags), it's got to be close.
For the deletion of an object out of (bags), which bags is a collection, you
can use a second bags2 a duplicate of the data in (bags), if you will.
Then this
int cnt = 0;
foreach(var bag in bags)
{
if (bag.ID == someID)
bags2.RemoveAt(idx);
cnt++;
}
I ended up with the following for Create, Get a Bag, Get many Bags,
Delete, and Update:
(Any suggestion to improve it is welcome).
private static readonly String path = "../Data/Bags.xml";
private static readonly XDocument context = XDocument.Load(path);
// Create
public void Create(Bag bag) {
// Create bag
XElement _bag = new XElement("Bag",
new XElement("Id", bag.Id == Guid.Empty ? Guid.NewGuid
().ToString() : bag.Id.ToString()),
new XElement("Content", bag.Content),
new XElement("Created", DateTime.UtcNow.ToString()),
new XElement("Name", bag.Name),
new XElement("Open", bag.Open.ToString()),
new XElement("Updated", DateTime.UtcNow.ToString())
);
context.Element("Bags").Add(_bag);
context.Save(path);
} // Create
// Delete
public void Delete(Guid id) {
// Delete bag
XElement bag = context.Root.Elements("Bags").FirstOrDefault(b =>
(String)b.Attribute("Id").Value == id.ToString());
if (bag != null) bag.Remove();
context.Save(path);
} // Delete
// GetBag
public Bag GetBag(Guid id) {
// Define bag
Bag bag = (from b in context.Elements("Bags")
where b.Element("Id").Value == id.ToString()
select new Bag {
Id = new Guid(b.Element("Id").Value),
Content = b.Element("Content").Value,
Created = DateTime.Parse(b.Element
("Created").Value),
Name = b.Element("Name").Value,
Open = Boolean.Parse(b.Element("Open").Value),
Updated = DateTime.Parse(b.Element
("Updated").Value)
}).SingleOrDefault();
return bag;
} // GetBag
// GetBags
public IQueryable<Bag> GetBags() {
// Define bags
IQueryable<Bag> bags = (from b in context.Elements("Bags")
orderby b.Element("Updated").Value
descending
select new Bag {
Id = new Guid(b.Element("Id").Value),
Content = b.Element("Content").Value,
Created = DateTime.Parse(b.Element
("Created").Value),
Name = b.Element("Name").Value,
Open = Boolean.Parse(b.Element
("Open").Value),
Updated = DateTime.Parse(b.Element
("Updated").Value)
}).AsQueryable();
return bags;
} // GetBags
// Update
public void Update(Bag bag) {
// Update bag
XElement _bag = context.Root.Elements("Bags").FirstOrDefault(b
=> (String)b.Attribute("Id").Value == bag.Id.ToString());
if (_bag != null) {
_bag.Attribute("Content").Value = bag.Content;
_bag.Attribute("Name").Value = bag.Name;
_bag.Attribute("Open").Value = bag.Open.ToString();
_bag.Attribute("Updated").Value = DateTime.UtcNow.ToString();
}
context.Save(path);
} // Update
Thanks,
Miguel