Doing CRUD on XML using id attributes in C# ASP.NET
Posted
by Brandon G
on Stack Overflow
See other posts from Stack Overflow
or by Brandon G
Published on 2010-04-13T18:07:05Z
Indexed on
2010/04/13
18:52 UTC
Read the original article
Hit count: 642
I'm a LAMP guy and ended up working this small news module for an asp.net site, which I am having some difficulty with. I basically am adding and deleting elements via AJAX based on the id. Before, I had it working based on the the index of a set of elements, but would have issues deleting, since the index would change in the xml file and not on the page (since I am using ajax).
Here is the rundown
news.xml
<?xml version="1.0" encoding="utf-8"?>
<news>
<article id="1">
<title>Red Shield Environmental implements the PARCSuite system</title>
<story>Add stuff here</story>
</article>
<article id="2">
<title>Catalyst Paper selects PARCSuite for its Mill-Wide Process...</title>
<story>Add stuff here</story>
</article>
<article id="3">
<title>Weyerhaeuser uses Capstone Technology to provide Control...</title>
<story>Add stuff here</story>
</article>
</news>
Page sending del request:
<script type="text/javascript">
$(document).ready(function () {
$('.del').click(function () {
var obj = $(this);
var id = obj.attr('rel');
$.post('add-news-item.aspx',
{ id: id },
function () {
obj.parent().next().remove();
obj.parent().remove();
}
);
});
});
</script>
<a class="del" rel="1">...</a>
<a class="del" rel="1">...</a>
<a class="del" rel="1">...</a>
My functions
protected void addEntry(string title, string story)
{
XmlDocument news = new XmlDocument();
news.Load(Server.MapPath("../news.xml"));
XmlAttributeCollection ids = news.Attributes;
//Create a new node
XmlElement newelement = news.CreateElement("article");
XmlElement xmlTitle = news.CreateElement("title");
XmlElement xmlStory = news.CreateElement("story");
XmlAttribute id = ids[0];
int myId = int.Parse(id.Value + 1);
id.Value = ""+myId;
newelement.SetAttributeNode(id);
xmlTitle.InnerText = this.TitleBox.Text.Trim();
xmlStory.InnerText = this.StoryBox.Text.Trim();
newelement.AppendChild(xmlTitle);
newelement.AppendChild(xmlStory);
news.DocumentElement.AppendChild(newelement);
news.Save(Server.MapPath("../news.xml"));
}
protected void deleteEntry(int selectIndex)
{
XmlDocument news = new XmlDocument();
news.Load(Server.MapPath("../news.xml"));
XmlNode xmlnode = news.DocumentElement.ChildNodes.Item(selectIndex);
xmlnode.ParentNode.RemoveChild(xmlnode);
news.Save(Server.MapPath("../news.xml"));
}
I haven't updated deleteEntry() and you can see, I was using the array index but need to delete the article element based on the article id being passed. And when adding an entry, I need to set the id to the last elements id + 1. Yes, I know SQL would be 100 times easier, but I don't have access so... help?
© Stack Overflow or respective owner