当文件由MemoryStream创建时,来自XML文件的编码属性声明变为小写

时间:2016-12-20 13:33:42

标签: c# .net xml memorystream

我必须使用Asp.Net Web API应用程序中的" ISO-8859-1" 编码生成XML文件,但MemoryStream会根据生成的XML定义来降低编码属性" iso-8859-1"

此方法基于由XSD创建的对象生成XML文件。

 public static MemoryStream GenerateXml<T>(T entity) where T : class
 {
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    //Add an empty namespace and empty value
    ns.Add("", "");

    var memoryStream = new MemoryStream();
    var streamWriter = new StreamWriter(memoryStream, Encoding.GetEncoding("ISO-8859-1"));
    var serializer = new XmlSerializer(typeof(T));

    serializer.Serialize(streamWriter, entity, ns);

    return memoryStream;
 }

然后我需要使用XDocument来替换XML元素的前缀定义(它的前提是所有元素都应该只用自己的标签命名)。所以我必须这样做:

 public MemoryStream GenerateXmlOpening<T>(T entity) where T : class
{
    var xmlMemStream = XmlHelper.GenerateXml(entity);

    xmlMemStream.Position = 0;
    XDocument doc = XDocument.Load(xmlMemStream, LoadOptions.PreserveWhitespace);
    //Removes the namespace declaration as prefix on elements
    doc.Descendants().Attributes().Where(a => a.IsNamespaceDeclaration).Remove();

    //the memory stream retreived from 'xmlMemStream' is already with "iso-8859-1 in lowercase, so im trying to override it
    doc.Declaration.Encoding = "ISO-8859-1";

    MemoryStream stream = new MemoryStream();

    // when i save the xdoc to the new memorystream, the encoding goes from "ISO-8859-1" to "iso-8859-1" again.
    doc.Save(stream);
    stream.Position = 0;

    return stream;
}

这是返回的生成的XML文件的开头:

<?xml version="1.0" encoding="iso-8859-1"?>
... content

它应该如何:

<?xml version="1.0" encoding="ISO-8859-1"?>
... content

Ps。*我正在使用MemoryStream编写XML,因为我必须编写.zip文件并返回此zip中所有生成的XML文件的响应。这个.Zip生成器接收一个MemoryStreams列表。

0 个答案:

没有答案