如何使xmlserializer仅序列化纯xml?


85

我需要获取纯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:


211

综上所述-这对我来说非常合适:

    // 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();
        }
    }

1
使用(var stream = new StringWriter())可以更改为var stream = new StringWriter(); 两次配置xmlwriter会给代码分析带来错误。
Archna

1
@Archna如果这样做,则在XmlWriter.Create调用引发异常的情况下,不会处理StringWriter。可能的解决方案涵盖了恶意的XmlWriter作者,使他们执行IDispose实现不符合保证两次执行Dispose对第二次调用不执行任何保证的问题,这将涉及try catch并将stream设置为null using( writer ),如下面的问题所示:stackoverflow.com/a/11192524/2144408
TamaMcGlinn

您将类型参数T用于什么?
杰斯珀

25

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

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

传递null或空数组将无法解决问题


7
请注意,您需要将此答案与@tobsen的答案结合起来才能得到我想要的-真正干净的xml!
Grzenio,


0

这会将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); 
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.