[英]How to serialize a XML without unnecessary spaces and line breaks? (.NET)
I'm using XmlSerializer.Serialize , and it produces line breaks and unnecessary spaces. 我正在使用XmlSerializer.Serialize ,它会产生换行符和不必要的空格。 How to avoid it?
怎么避免呢?
Perhaps you could use the overload accepting an XmlWriter
, and configure the given XmlWriter
with an XmlWriterSettings
instance? 也许你可以使用过载受理
XmlWriter
,并配置给定XmlWriter
与XmlWriterSettings
实例?
XmlWriterSettings
allows you to control the application of line breaks and indentation. XmlWriterSettings
允许您控制换行符和缩进的应用程序。
void Serialize(Object o)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.NewLineHandling = NewLineHandling.None;
//settings.OtherProperties = values;
using (XmlWriter writer = XmlWriter.Create(CreateStream(), settings))
{
_serializer.Serialize(writer, o);
}
}
It's interesting, I thought there was no formatting by default. 有趣的是,我认为默认情况下没有格式化。 I just tried the following and got no formatting:
我刚刚尝试了以下内容并且没有格式化:
using (var stream = new MemoryStream())
{
System.Text.Encoding encoding;
using (var writer = XmlWriter.Create(stream))
{
if (writer == null)
{
throw new InvalidOperationException("writer is null");
}
encoding = writer.Settings.Encoding;
var ser = new XmlSerializer(obj.GetType());
ser.Serialize(writer, obj);
}
stream.Position = 0;
using (var reader = new StreamReader(stream, encoding, true))
{
return reader.ReadToEnd();
}
}
in a sample run, it returned the following XML: 在示例运行中,它返回以下XML:
<?xml version="1.0" encoding="utf-8"?><obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><childOne /><childTwo /><text>text1</text><text>text2</text></obj>
Please also check if serialized classes contain members of XML-type (like XmlElement). 还请检查序列化类是否包含XML类型的成员(如XmlElement)。 I used Xsd2Code tool to generate classes from XSD and (in very special case) it has created a member of type XmlElement.
我使用Xsd2Code工具从XSD生成类,并且(在非常特殊的情况下)它创建了一个XmlElement类型的成员。 During serialization this member had its own formatting (identation to be exact).
在序列化期间,该成员具有自己的格式(确切地说是标识)。 Even if I had turned on (or off) XmlSerializer indentation it had no affect on the XmlElement member.
即使我打开(或关闭)XmlSerializer缩进,它也不会影响XmlElement成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.