我正在使用的文件格式 (OFX) 类似于 XML,并且在类似于 XML 的位开始之前包含一堆纯文本内容。它不喜欢在纯文本和 XML 部分之间存在,所以我想知道是否有办法让 XmlSerialiser 忽略它。我知道我可以浏览文件并清除该行,但首先不写它会更简单、更清晰!有任何想法吗?
问问题
258 次
2 回答
6
您必须在调用该Serialize
方法时操作您使用的 XML 编写器对象。它的Settings
属性有一个OmitXmlDeclaration
属性,您需要将其设置为 true。您还需要设置该ConformanceLevel
属性,否则 XmlWriter 将忽略该OmitXmlDeclaration
属性。
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlWriter writer = XmlWriter.Create(/*whatever stream you need*/,settings);
serializer.Serialize(writer,objectToSerialize);
writer.close();
于 2009-09-09T13:31:18.473 回答
4
不太难,您只需序列化为显式声明的 XmlWriter 并在序列化之前设置该 writer 的选项。
public static string SerializeExplicit(SomeObject obj)
{
XmlWriterSettings settings;
settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializerNamespaces ns;
ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer;
serializer = new XmlSerializer(typeof(SomeObject));
//Or, you can pass a stream in to this function and serialize to it.
// or a file, or whatever - this just returns the string for demo purposes.
StringBuilder sb = new StringBuilder();
using(var xwriter = XmlWriter.Create(sb, settings))
{
serializer.Serialize(xwriter, obj, ns);
return sb.ToString();
}
}
于 2009-09-09T13:32:34.760 回答