Hello,
I used a static class to implement the above three functions.
You can refer to the following key code and annotations.
// The xml file format written by this method is
// <? xml version = "1.0" encoding = "UTF-8"?>
// <site>
// <name> test.txt </name>
// <name> Filename.txt </name>
// </site>
// If you need to adjust the XML file format, you can refer to this method for modification.
public static class ListXMLHelper
{
public static void WriteStringsToXML(string filename, List<string> strings)
{
StringBuilder myStringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
myStringBuilder.AppendLine();
myStringBuilder.AppendLine("<site>");
foreach (string s in strings) {
myStringBuilder.Append(" <name>");
myStringBuilder.Append(s);
myStringBuilder.Append("</name>");
myStringBuilder.AppendLine();
}
myStringBuilder.AppendLine("</site>");
using (StreamWriter outputFile = new StreamWriter(filename))
{
outputFile.Write(myStringBuilder.ToString());
}
}
public static List<string> ReadStringsToXML(string filename) {
List<string> strs = new List<string>();
using (StreamReader inputFile = new StreamReader(filename))
{
while (!inputFile.EndOfStream) {
var s = inputFile.ReadLine();
// get value from <name></name>
var value = GetContent(s, "name");
if (value != null) {
strs.Add(value);
}
}
}
return strs;
}
// Get the value in the XML label through a regular expression.
public static string GetContent(string str, string title)
{
string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", title, title); //获取<title>之间内容
Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
string result = TitleMatch.Groups["Text"].Value;
if (result.Length > 0) {
return result;
}
else
{
return null;
}
}
// delete the file
public static void DeleteFile(string filename) {
if (File.Exists(filename))
{
File.Delete(filename);
}
}
}
Please refer to the following documentations:
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.