.NET MAUI
一种 Microsoft 开源框架,用于构建跨移动设备、平板电脑、台式机的原生设备应用程序。
50 个问题
你好
我有要转换为 xml 并保存到磁盘的字符串(文件名)列表。
我想从磁盘读取此 xml 并转换为字符串列表。
我想从磁盘中删除此 xml。
提前致谢,
你好,
我使用了一个静态类来实现上述三个函数。
您可以参考以下键代码和注释。
// 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:
如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。 注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。