背景
我使用Dictionary作为lookuptable,在stackoverflow的帮助下,我能够序列化该对象。 我使用XDocument.Parse将xmlstring转换为XDocument并将文件保存到硬盘。
问题
字典有一个带空格的键" "并且DataContractSerializer按预期工作,但XDocument删除空间" "
带注释的代码
namespace TestIssue001
{
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
[DataContract]
class RemoteData
{
[DataMember]
public Dictionary<string, string> Dictionary { get; set; }
}
class Program
{
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
public static string GenerateXmlResponsewithnested(RemoteData remotedata)
{
var xml = "";
var serializer = new DataContractSerializer(typeof(RemoteData));
using (var sw = new Utf8StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented; // indent the Xml so it's human readable
serializer.WriteObject(writer, remotedata);
writer.Flush();
xml = sw.ToString();
}
}
return xml;
}
static void Main(string[] args)
{
RemoteData remoteData = new RemoteData();
remoteData.Dictionary = new Dictionary<string, string> { { " ", "Whitespace" } };
// The xml string contains the space character ' ' as key
string xmlstring = GenerateXmlResponsewithnested(remoteData);
// In the doc the space character ' ' as key i removed
XDocument doc = XDocument.Parse(xmlstring);
doc.Save(@".\myconfig.xml");
}
}
}
变量xmlstring
<RemoteData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/TestIssue001">
<Dictionary xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:KeyValueOfstringstring>
<d2p1:Key> </d2p1:Key>
<d2p1:Value>Whitespace</d2p1:Value>
</d2p1:KeyValueOfstringstring>
</Dictionary>
</RemoteData>
可变文档
<RemoteData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/TestIssue001">
<Dictionary xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:KeyValueOfstringstring>
<d2p1:Key></d2p1:Key>
<d2p1:Value>Whitespace</d2p1:Value>
</d2p1:KeyValueOfstringstring>
</Dictionary>
</RemoteData>
问题
我如何通知XDocument将空格字符保留为键?
答案 0 :(得分:4)
我如何通知XDocument将空格字符保留为键?
XDocument doc = XDocument.Parse(xmlstring, LoadOptions.PreserveWhitespace);