97

我需要得到普通的 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。我该怎么做?

4

4 回答 4

236

把这一切放在一起 - 这对我来说非常有用:

    // 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();
        }
    }
于 2010-09-17T02:10:32.217 回答
27

使用XmlSerializer.Serialize方法重载,您可以在其中指定自定义命名空间并将其传递给那里。

var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);

传递 null 或空数组不会成功

于 2009-11-22T22:11:39.267 回答
15

您可以使用XmlWriterSettings并将属性OmitXmlDeclaration设置为 true,如 msdn 中所述。然后使用此处描述的XmlSerializer.Serialize(xmlWriter, objectToSerialize)

于 2009-11-20T17:49:15.290 回答
1

这会将 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); 
}
于 2019-07-15T15:43:33.800 回答