问题
In my web application, i have an XML file called "answers.xml"
it store the 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 the XML file using a DLL file i downloaded from the internet. i need a way to change the data (edit / delete) in the xml file using ASP.net / VB.net or C#
回答1:
I prefer to use XDocument, because simply you can search it and change the 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 AnswerSet elements, Elements("Answer") finds Answer Elements,
Where(x => x.Attribute("FName") != null
&& x.Attribute("FName").Value == "test").SingleOrDefault();
finds element which contains attribute FName
and attribute value equals to test
, SingleOrDefault
in the last, says you should have just one such an element, Also you can change it (just call ToList()
) to find all related elements, and finally in if
I'll change the value of element, Also at the end we save it again with changed values.
This language (linq2xml) is too easy and functions like Descendant
and Elements
are most use full functions in it, so there is no need to have special knowledge you can simply come up to many problems by knowing this functions.
回答2:
You can just use the XmlDocument class that comes with .Net. No need to download something. Or do I miss something?
First thing I found, it's for VB, but the concept stays the same for c#.
http://support.microsoft.com/kb/317662
You can just load any xml file and then use XPath to access any node and change it.
回答3:
Have you looked at the XmlDataSource Control.
来源:https://stackoverflow.com/questions/8058182/edit-and-delete-data-from-xml-file-using-asp-net-and-vb-net-or-c