Editing and deleting data from an XML file using ASP.net and VB.net (or C #)

In my web application , I have an XML file called "answers.xml"

it stores user entries in XML

<?xml version=""1.0""?> <Answers> <AnswerSet> <Answer questionId=""MRN"">4444</Answer> <Answer questionId=""FName"">test</Answer> <Answer questionId=""LName"">patient</Answer> <Answer questionId=""AddressPt"">blah blah</Answer> <Answer questionId=""Governorate"">xxxx</Answer> <Answer questionId=""InitialCSF"">Negative</Answer> <Answer questionId=""Diagnosis""></Answer> <Answer questionId=""Description""> </Answer> </AnswerSet> <AnswerSet> <Answer questionId=""MRN"">1</Answer> <Answer questionId=""FName"">1</Answer> <Answer questionId=""LName"">1</Answer> <Answer questionId=""AddressPt"">1</Answer> <Answer questionId=""InitialCSF"">Positive</Answer> <Answer questionId=""Diagnosis"">dx</Answer> <Answer questionId=""Description""> </Answer> </AnswerSet> </Answers> 

I can add data to an XML file using a DLL file downloaded from the Internet. I need a way to change data (edit / delete) in an XML file using ASP.net/VB.net or C #

+4
source share
3 answers

I prefer to use XDocument , because simply you can search for it and change elements or attributes:

 XDocument doc1 = XDocument.Parse("<AnswerSet> <Answer questionId=\"10\" FName=\"test\"> </Answer></AnswerSet> "); // or if you have related file simply use XDocument doc1 = XDocument.Load(fileFullName); var element = doc1.Descendants("AnswerSet").Elements("Answer") .Where(x => x.Attribute("FName") != null && x.Attribute("FName").Value == "test").SingleOrDefault(); if (element != null) { var attr = element.Attribute("FName"); attr.Value = "Changed"; } doc1.Save(filePath); 

Edit: Descendants("AnswerSet") finds the response items, Elements ("Answer") finds the response items,

 Where(x => x.Attribute("FName") != null && x.Attribute("FName").Value == "test").SingleOrDefault(); 

finds an element that contains the FName attribute, and the attribute value is test , SingleOrDefault in the latter, says that you should have only one such element. You can also change it (just call ToList() ) to find all the related elements and, finally, in the if changes the value of the element. Also at the end we save it again with the changed values.

This language (linq2xml) is too simple, and functions such as Descendant and Elements , most of all use the full functions in it, so there is no need to have special knowledge that you can just find in many problems, knowing these functions.

+3
source

You can simply use the XmlDocument class that comes with .Net. No need to download anything. Or am I missing something?

The first thing I found is for VB, but the concept remains the same for C #.
http://support.microsoft.com/kb/317662

You can simply load any XML file, and then use XPath to access any node and modify it.

+2
source

You looked at the XmlDataSource control.

+1
source

Source: https://habr.com/ru/post/1380288/


All Articles