问题
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.
[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>
回答1:
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. The easiest fix is to remove the xmlrootattribute;
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();
}
}
来源:https://stackoverflow.com/questions/49556390/c-sharp-serializer-not-adding-prefix-to-root-element