簡體   English   中英

C#序列化程序未向根元素添加前綴

[英]C# serializer not adding prefix to root element

看到很多人都遇到同樣的問題,卻在任何地方都沒有答案,所以我自己在這里回答;

序列化應附加前綴的XML類時,前綴會丟失。

[XmlRoot(ElementName = "Preadvice", Namespace = "http://www.wibble.com/PreadviceRequest")]
public class Preadvice
{
}

var XMLNameSpaces = new XmlSerializerNamespaces();
XMLNameSpaces.Add("isd", "http://www.wibble.com/PreadviceRequest");

這是我的序列化方法;

public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns, XmlAttributeOverrides xao, XmlRootAttribute xra)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T), (xao == null ? new XmlAttributeOverrides() : xao), new Type[] { obj.GetType() }, (xra == null ? new XmlRootAttribute(obj.GetType().Name) : xra), "");

    using (StringWriter sw = new StringWriter())
    {
        using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
        {
            serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
        }
        return sw.ToString();
    }
}

這產生了;

<?xml version="1.0" encoding="utf-16"?>
<Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</Preadvice>

缺少前綴,它應該看起來像這樣。

<?xml version="1.0" encoding="utf-16"?>
<isd:Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</isd:Preadvice>

如果序列化程序在創建時包含xmlroot屬性,則它不應用您手動指定的名稱空間,因此會丟失第一個元素的“ isd”標記。 最簡單的解決方法是刪除xmlroot屬性。

public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StringWriter sw = new StringWriter())
    {
        using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
        {
            serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
        }
        return sw.ToString();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM