我需要编写一个 XML 片段以供 Web 服务使用。任何 xml 声明都会导致 Web 服务拒绝请求。为了支持这一点,我有以下课程:
public class ContentQueryCriteria
{
public int Type { get; set; }
public string Value { get; set; }
public int Condition { get; set; }
}
这允许我设置请求标准,然后得到结果。
代码是这样使用的:
ContentQueryCriteria content = new ContentQueryCriteria();
content.Type = 1;
content.Value = "NAVS500";
content.Condition = 1;
string requestBody = SerializeToString(content);
Console.WriteLine(requestBody);
当我将其序列化为 XML 文件时,我得到了正确的响应,没有 XML 声明或任何命名空间。但是,我宁愿在内存流中捕获数据,而不是在文件中。
使用以下方法(取自http://www.codeproject.com/Articles/58287/XML-Serialization-Tips-Tricks)我能够取得结果,但由于某种原因我有一个?列为字符串的一部分。
public static string SerializeToString(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Encoding = Encoding.Unicode;
XmlWriter writer = XmlWriter.Create(ms, settings);
serializer.Serialize(writer, obj, ns);
return Encoding.Unicode.GetString(ms.ToArray());
}
结果字符串是:
?<ContentQueryCriteria><Type>1</Type><Value>NAVS500</Value><Condition>1</Condition></ContentQueryCriteria>
如果我设置 OmitXmlDeclaration = false 我得到以下字符串:
?<?xml version="1.0" encoding="utf-16"?><ContentQueryCriteria><Type>1</Type><Value>NAVS500</Value><Condition>1</Condition></ContentQueryCriteria>
谁能帮我确定为什么额外的?有吗?我怎样才能删除它?
没有 BOM 的工作 SerializeToString 方法
public static string SerializeToString(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Encoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: false);
XmlWriter writer = XmlWriter.Create(ms, settings);
serializer.Serialize(writer, obj, ns);
return Encoding.Unicode.GetString(ms.ToArray());
}