[英]C# serializer not adding prefix to root element
Seen lots of people with this same issue and no answers anywhere, so answering it myself here; 看到很多人都遇到同样的问题,却在任何地方都没有答案,所以我自己在这里回答;
When serializing an XML class that should have a prefix attached to it, the prefix is missing. 序列化应附加前缀的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");
And this is my serializing method; 这是我的序列化方法;
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();
}
}
This produces; 这产生了;
<?xml version="1.0" encoding="utf-16"?>
<Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</Preadvice>
Which is missing the prefix, it should look like this.. 缺少前缀,它应该看起来像这样。
<?xml version="1.0" encoding="utf-16"?>
<isd:Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</isd:Preadvice>
If your serializer includes an xmlrootattribute when it is created, it doesn't apply namespaces you have specified manually, and therefore misses the "isd" tag off the first element. 如果序列化程序在创建时包含xmlroot属性,则它不应用您手动指定的名称空间,因此会丢失第一个元素的“ isd”标记。 The easiest fix is to remove the xmlrootattribute; 最简单的解决方法是删除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.