simplemente me encontré con este problema. En mi caso, el XML es generado por el control del código I, así que pude agregar el atributo xml: space = preserve. Estaba usando IXmlSerializable (por una buena razón que no entraré aquí). Así es como lo hice, en caso de que sea útil para alguien (es difícil encontrar ejemplos de gran parte de esta serialización/deserialización Xml). El método WriteXml() utiliza este método WriteSettings() para implementar IXmlSerializable.
public static void WriteSettings(XmlWriter writer, Dictionary<string, string> settings)
{
foreach (string key in settings.Keys)
{
string value = settings[key];
writer.WriteStartElement("Setting");
writer.WriteElementString("SettingType", key);
//writer.WriteElementString("SettingValue", value);
// I replaced the above line, which I had previously,
// with the below 5 lines.
writer.WriteStartElement("SettingValue");
if (value != value.Trim())
writer.WriteAttributeString("xml", "space", null, "preserve");
writer.WriteString(value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
Esto me da XML que tiene este aspecto (elemento que encierra escrita encerrando objeto, no el método WriteSettings arriba):
<ResourceSettings>
<Setting>
<SettingType>SomeSettingName</SettingType>
<SettingValue>1</SettingValue>
</Setting>
<Setting>
<SettingType>AnotherSettingName</SettingType>
<SettingValue xml:space="preserve"> </SettingValue>
</Setting>
<Setting>
<SettingType>ADifferentSettingName</SettingType>
<SettingValue>some other value</SettingValue>
</Setting>
</ResourceSettings>
leí esto en el uso del mismo código que tenía antes y el XmlReader respeta el xml: espacio = preservar atributo, por ejemplo:
public void ReadXml(XmlReader reader)
{
_cache = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "ResourceSettings")
{
// Deal with the case where there are no settings
if (reader.ReadToDescendant("Setting"))
{
while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Setting")
{
reader.ReadStartElement("Setting");
string key = reader.ReadElementString("SettingType");
string value = reader.ReadElementString("SettingValue");
reader.ReadEndElement();
_cache.Add(key, value);
}
}
reader.Read(); // move past container
}
}