2

Based on the index in the controller, how would I append a record to an XML file? I've done some research, but I can't seem to wrap my head around it.

Index(controller)

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

What I've tried:

Create(Controller)

    [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();
        }
    }

I am bad at syntax so this is probably all wrong.

4
  • Do you want to append or update that specific record? Commented Sep 27, 2018 at 15:21
  • Add a record, I have a view to create a record, I just want to append the record to the file, and I don't know where to start at. Commented Sep 27, 2018 at 15:25
  • There are a few ways to go about that, I personal use Element for such scenarios, load the parent element, add the child, and then save the file. You can also add an xml element as a child. Commented Sep 27, 2018 at 15:31
  • Example please if you can. Commented Sep 27, 2018 at 16:02

1 Answer 1

1

For starters that are a few classes available in C#, suing the specific class that you are using, you should be able to do the following

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

That will append the value to your xmlFile, the NameOfParentTag is the name of the parentLocation where you want to insert the value, in your case I would assume that would be record

The second way would be

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

where the SerializeAsXml method looks like

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, for the above method you would need to decorate your XML with the necessary attributes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.