【发布时间】:2017-05-21 19:21:23
【问题描述】:
我正在尝试在递归函数中使用 XmlWriter 在 C# 中编写 XML 文件。该文件应该包含给定目录中的每个文件夹以及每个子文件夹和文件。
我在尝试在 XML 文件中写入特殊字符时遇到了一些麻烦,它不断地给我一个错误,
我不能使用'&'、'/'、'-'、'.'、''等字符。
偶数不起作用。我尝试找到与此问题类似的问题,但没有解决方案对我有帮助,我尝试替换包含特殊字符的文件夹和/或文件字符串名称,并使用“&”、“"”、“'”转义它们等等,但这也不起作用。它只是给我一个错误,我不能使用'&'。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
namespace XMLgenerator
{
public class Generator
{
public void write(string Dir, XmlWriter writer)
{
try
{
writer.WriteStartElement("Folders");
foreach (string s in Directory.GetDirectories(Dir))
{
string[] splitter = s.Split('\\');
string ss = splitter[splitter.Length - 1];
string ssxml = XmlConvert.EncodeLocalName(ss);
writer.WriteStartElement("Folder");
writer.WriteAttributeString("name", ssxml);
foreach (string f in Directory.GetFiles(s))
{
string fxml = XmlConvert.EncodeLocalName(f);
FileInfo fi = new FileInfo(f);
long length = fi.Length;
writer.WriteElementString(fxml, length.ToString());
}
writer.WriteEndElement();
write(s,writer);
}
writer.WriteEndElement();
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
return;
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return;
}
}
// Method for creating an XML file and also getting directories and files. File name and dir path are parametres
public void generateContent(string Dir)
{
XmlWriterSettings xws = new XmlWriterSettings();
xws.Encoding = new UTF8Encoding();
using (XmlWriter writer = XmlWriter.Create("test.xml", xws))
{
writer.WriteStartDocument();
write(Dir,writer);
writer.WriteEndDocument();
}
}
}
}
【问题讨论】:
-
;之前的空格使转义字符无效。&是 '&' 而&amp ;是 '&'还有HttpUtility.HtmlEncode and System.Security.SecurityElement.Escape,因此您无需为每个可能的无效字符编码。 -
嘿,保罗,我刚刚在这个问题中留出了那个空间,因为没有它它会在这里正确翻译,所以它不是 &,而是给出了实际的 &