将记录追加到Xml ASP.Net MVC5

时间:2018-09-27 15:01:29

标签: c# asp.net xml razor model-view-controller

基于控制器中的索引,如何将记录追加到XML文件中?我已经做过一些研究,但似乎无法解决这个问题。

索引(控制器)

public ActionResult Index(string sortOrder)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("C:\\Users\\Matt.Dodson\\Desktop\\SampleWork\\PersonsApplicationFromXMLFile\\PersonsApplicationFromXMLFile\\DAL\\Personal.xml");
    IEnumerable<Personal> persons = doc.SelectNodes("/Persons/record").Cast<XmlNode>().Select(node => new Personal()
    {
        ID = node["ID"].InnerText,
        Name = node["Name"].InnerText,
        Email = node["Email"].InnerText,
        DateOfBirth = node["DateOfBirth"].InnerText,
        Gender = node["Gender"].InnerText,
        City = node["City"].InnerText
    });

    switch (sortOrder)
    {
        case "ID":
            persons = persons.OrderBy(Personal => Personal.ID);
            break;

        case "Name":
            persons = persons.OrderBy(Personal => Personal.Name);
            break;

        case "City":
            persons = persons.OrderBy(Personal => Personal.City);
            break;

        default:
            break;
    }

    return View(persons.ToList());
}

我尝试过的事情:

创建(控制器)

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        string xmlFile = "C:\\Users\\Matt.Dodson\\Desktop\\SampleWork\\PersonsApplicationFromXMLFile\\PersonsApplicationFromXMLFile\\DAL\\Personal.xml";
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);
            IEnumerable<Personal> persons = doc.SelectNodes("/Persons/record")
                .Cast<XmlNode>()
                .Select(node => new Personal()
                {
                    ID = node["ID"].InnerText,
                    Name = node["Name"].InnerText,
                    Email = node["Email"].InnerText,
                    DateOfBirth = node["DateOfBirth"].InnerText,
                    Gender = node["Gender"].InnerText,
                    City = node["City"].InnerText
                });
            persons.appendTo(xmlFile);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

我的语法不好,所以这可能全错了。

1 个答案:

答案 0 :(得分:1)

对于C#中可用的少数几个入门类,请使用您正在使用的特定类,您应该能够执行以下操作

XDocument doc = XDocument.Load(xmlFile);
        var parent = doc.Descendants("NameOfParentTag").FirstOrDefault();//if there is only one
        parent.Add(new XElement("personal",
            new XElement("ID", ID_Value),
            new XElement("Name" = Name_Value),
            new XElement("Email", Email_value)));
        doc.Save(xmlFile);

这会将值附加到您的xmlFile中,NameOfParentTag是您要在其中插入值的parentLocation的名称,在这种情况下,我假设它将是record

第二种方法是

doc.Load(xmlFile);
                XmlNode editNode = doc.SelectSingleNode("targetNode");
                XmlNode node = nodes[0];//get the specific node, not sure about your xml structure
                XmlElement elem = node.OwnerDocument.CreateElement("personal");
                elem.InnerXml = personal.SerializeAsXml();
                node.AppendChild(elem);

SerializeAsXml方法的外观

public static string SerializeAsXml(this Personal personal)
        {
            var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            //serialize the binding
            string xmlOutput = string.Empty;
            using (StringWriter stream = new StringWriter())
            using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
            {
                XmlSerializer serializer = new XmlSerializer(personal.GetType());
                serializer.Serialize(xmlWriter, obj, emptyNamepsaces);
                xmlOutput = stream.ToString();
            }

            return xmlOutput;
        }

NB ,对于上述方法,您需要使用必要的attributes

装饰XML