如何使用XMLSerializer添加没有前缀的默认命名空间

时间:2010-03-23 13:16:10

标签: c# namespaces xmlserializer

我正在尝试生成一个XML文档,该文档包含使用XmlSerializer的没有前缀的默认命名空间,例如

<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord">
    <List>
        <SpecificItem>

使用以下代码......

string xmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord));
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, string.Empty);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray());

和班级结构......

[Serializable]
[XmlRoot("MyRecord")]
public class ExportMyRecord
{
    [XmlAttribute("ID")]
    public int ID { get; set; }

现在,我尝试了各种选择......

XmlSerializer xs = new XmlSerializer
                     (typeof(ExportMyRecord),"http://www.website.com/MyRecord");

或......

[XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")]

给了我......

<?xml version="1.0" encoding="utf-8"?>
<q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord">
    <q1:List>
        <q1:SpecificItem>

我需要XML才能拥有没有前缀的命名空间,因为它会转到第三方提供商,并拒绝所有其他选择。

2 个答案:

答案 0 :(得分:32)

你去了:

ExportMyRecord instance = GetInstanceToSerializeFromSomewhere();
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.website.com/MyRecord");
var serializer = new XmlSerializer(
    instance.GetType(), 
    "http://www.website.com/MyRecord"
);

答案 1 :(得分:0)

这是可以用于任何类型的通用实现:

public static void Serialize<T>(T instance, string defaultNamespace, Stream stream)
{
    var namespaces = new XmlSerializerNamespaces();
    namespaces.Add(string.Empty, defaultNamespace);
    var serializer = new XmlSerializer(typeof(T), defaultNamespace);
    serializer.Serialize(stream, instance, namespaces);
}