使用C#ASP.NET中的id属性对XML执行CRUD

时间:2010-04-13 18:07:05

标签: c# asp.net xml

我是一个LAMP人,最后在asp.net网站上使用这个小新闻模块,我遇到了一些困难。我基本上是基于id通过AJAX添加和删除元素。之前,我让它基于一组元素的索引工作,但是会有删除问题,因为索引会在xml文件中更改而不在页面上(因为我使用的是ajax)。

这是破败的

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>

页面发送del请求:

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

我的功能

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

我没有更新deleteEntry(),你可以看到,我正在使用数组索引,但需要根据传递的文章ID删除article元素。在添加条目时,我需要将id设置为最后一个元素id + 1.是的,我知道SQL会容易100倍,但我没有访问权限......帮助?

2 个答案:

答案 0 :(得分:3)

Linq to XML应该让这更加简单。这将等同于您的尝试:

        public void AddEntry(string title, string story)
        {
            var newElement = new XElement("article", new XElement("title", title), new XElement("story", story));                
            XDocument doc = XDocument.Parse(testXml);
            var maxId = doc.Descendants("article").Attributes("id").Max(x => int.Parse(x.Value));
            newElement.Add(new XAttribute("id", ++maxId));
            doc.Descendants("news").First().Add(newElement);
            //save the document
        }

        public void DeleteEntry(int selectIndex)
        {
            XDocument doc = XDocument.Parse(testXml);
            doc.Descendants("article").Where(x => int.Parse(x.Attribute("id").Value) == selectIndex).Remove();
            //save the document
        }

根据xml文件的大小和请求数量,您可能希望查看除加载文档之外的其他方法,并为每次添加和删除的调用保存它。

编辑:请注意,您需要在上面的代码中添加空检查...

答案 1 :(得分:0)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace LinqToXML
{
    class Program
    {
        static void Main(string[] args)
        {
            int ch;
            do
            {
                Console.WriteLine("Enter the operation you want to execute");

                Console.WriteLine("Press 1 to show previous record");
                Console.WriteLine("Press 2 to add new record");
                Console.WriteLine("Press 3 to delete record");
                Console.WriteLine("Press 4 to update record");

                Record RecordObject = new Record();

                int UserChoice = Convert.ToInt32(Console.ReadLine());

                switch (UserChoice)
                {
                    case 1:
                        RecordObject.ShowRecord();

                        break;

                    case 2:
                        RecordObject.AddRecord();

                        break;

                    case 3:
                        RecordObject.DeleteRecord();

                        break;

                    case 4:
                        RecordObject.UpdateRecord();

                        break;

                    default:
                        Console.WriteLine("Invalid Option");
                        break;
                }

                Console.WriteLine("\tDo you Want to CONTINUE?\n\t1.YES\n\t2.NO");
                ch = Convert.ToInt32(Console.ReadLine());
            } while (ch == 1);
        }
    }

    class Info
    {
        public string StudentName { get; set; }
        public int StudentId { get; set; }
        public int StudentAge { get; set; }
        public string StudentCity { get; set; }
    }

    class Record
    {
        string fileAddress = @"C:\XML.xml";
        XmlDocument doc = new XmlDocument();

        public void ShowRecord()
        {
            if (File.Exists(fileAddress))
            {
                string line;
                using (StreamReader sr = new StreamReader(fileAddress))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("No record exist");
            }
        }

        public void AddRecord()
        {
            Console.WriteLine("Enter Student Name :");
            string StuName = Console.ReadLine();

            Console.WriteLine("Enter Student Age :");
            int StuAge = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Student City :");
            string StuCity = Console.ReadLine();

            Info InfoObj = new Info();

            InfoObj.StudentName = StuName;
            InfoObj.StudentAge = StuAge;
            InfoObj.StudentCity = StuCity;


            FileStream FileStreamObj = null;

            if (File.Exists(fileAddress))
            {
                FileStreamObj = new FileStream(fileAddress, FileMode.Open, FileAccess.ReadWrite);
                FileStreamObj.Close();

                XmlDocument doc = new XmlDocument();
                doc.Load(fileAddress);

                XmlNodeList nodes = doc.SelectNodes("//students/student");
                int nodeCount = nodes.Count;
                nodeCount++;


                XmlNodeList students = doc.SelectNodes("//students");
                foreach (XmlNode student in students)
                {

                    XmlNode parentNode = doc.CreateElement("student");

                    XmlAttribute attribute = doc.CreateAttribute("id");
                    attribute.Value = nodeCount.ToString();
                    parentNode.Attributes.Append(attribute);
                    student.AppendChild(parentNode);

                    XmlNode studentName = doc.CreateElement("studentName");
                    studentName.InnerText = StuName;
                    parentNode.AppendChild(studentName);

                    XmlNode studentAge = doc.CreateElement("studentAge");
                    studentAge.InnerText = StuAge.ToString();
                    parentNode.AppendChild(studentAge);

                    XmlNode studentCity = doc.CreateElement("studentCity");
                    studentCity.InnerText = StuCity;
                    parentNode.AppendChild(studentCity);

                    doc.Save(fileAddress);

                }
            }
            else
            {
                FileStreamObj = new FileStream(fileAddress, FileMode.Create, FileAccess.ReadWrite);
                FileStreamObj.Close();

                int StudentId = 1;

                XmlDocument doc = new XmlDocument();

                XmlNode rootNode = doc.CreateElement("students");
                doc.AppendChild(rootNode);

                XmlNode parentNode = doc.CreateElement("student");
                XmlAttribute attribute = doc.CreateAttribute("id");
                attribute.Value = StudentId.ToString();
                parentNode.Attributes.Append(attribute);
                rootNode.AppendChild(parentNode);

                XmlNode studentName = doc.CreateElement("studentName");
                studentName.InnerText = StuName;
                parentNode.AppendChild(studentName);

                XmlNode studentAge = doc.CreateElement("studentAge");
                studentAge.InnerText = StuAge.ToString();
                parentNode.AppendChild(studentAge);

                XmlNode studentCity = doc.CreateElement("studentCity");
                studentCity.InnerText = StuCity;
                parentNode.AppendChild(studentCity);

                doc.Save(fileAddress);
            }
        }

        public void UpdateRecord()
        {
            doc.Load(fileAddress);
            Console.WriteLine("Enter ID of the record you want to update");
            int InputChoice = Convert.ToInt32(Console.ReadLine());

            Info infoObj = new Info();

            XmlElement element = doc.DocumentElement;
            XmlNode nodeElement = element.SelectSingleNode("student[@id='" + InputChoice + "']");

            if (nodeElement == null)
            {
                Console.WriteLine("Record doesn't exist");
            }
            else
            {
                string oldName = nodeElement.ChildNodes[0].InnerText;
                string oldAge = nodeElement.ChildNodes[1].InnerText;
                string oldCity = nodeElement.ChildNodes[2].InnerText;

                infoObj.StudentName = oldName;
                infoObj.StudentAge = Convert.ToInt32(oldAge);
                infoObj.StudentCity = oldCity;

                Console.WriteLine("Old Values are:\n\tName: " + infoObj.StudentName + "\n\tAge" + infoObj.StudentAge + " \n\tCity" + infoObj.StudentCity + "");

                Console.WriteLine("Enter new name");
                string newName = Console.ReadLine();
                Console.WriteLine("Enter new Age");
                int newAge = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter new city");
                string newCity = Console.ReadLine();

                infoObj.StudentName = newName;
                infoObj.StudentAge = newAge;
                infoObj.StudentCity = newCity;

                nodeElement.ChildNodes[0].InnerText = infoObj.StudentName;
                nodeElement.ChildNodes[1].InnerText = infoObj.StudentAge.ToString();
                nodeElement.ChildNodes[2].InnerText = infoObj.StudentCity;

                doc.Save(fileAddress);
            }
        }

        public void DeleteRecord()
        {
            doc.Load(fileAddress);

            Console.WriteLine("Enter the Id you want to delete");
            string inputValue = Console.ReadLine();

            XmlElement element = doc.DocumentElement;
            XmlNode nodeElement = element.SelectSingleNode("student[@id='" + inputValue + "']");
            if (nodeElement == null)
            {
                Console.WriteLine("Record doesn't exist");
            }
            else
            {
                element.RemoveChild(nodeElement);
                doc.Save(fileAddress);
                Console.WriteLine("Sucessfully deleted");
            }

        }
    }

}