我需要获取纯xml,而<?xml version="1.0" encoding="utf-16"?>
在开头和xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
第一个元素中都没有XmlSerializer
。我该怎么做?
Answers:
综上所述-这对我来说非常合适:
// To Clean XML
public string SerializeToString<T>(T value)
{
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamespaces);
return stream.ToString();
}
}
using( writer )
,如下面的问题所示:stackoverflow.com/a/11192524/2144408。
这会将XML写入文件而不是字符串。对象票据是我要序列化的对象。
使用的命名空间:
using System.Xml;
using System.Xml.Serialization;
码:
XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(ticket));
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (XmlWriter xmlWriter = XmlWriter.Create(fullPathFileName, settings))
{
serializer.Serialize(xmlWriter, ticket, emptyNamespaces);
}