简体   繁体   中英

Can I add a prefix to root element when I have no control over the serialized .NET type?

I have a library that contains a .NET type. The library has its own configuration (annotations etc) for serializing the type to XML, and I do not have the source code.

No matter what I do, I could not manage to add the prefix I want to add to the root element of the output XML. Using XmlSerializerNamespaces made no difference. Here is a snippet that shows my code at the moment:

                    var comp = row[0] as LibraryType;
                    var ser = new XmlSerializer(comp.GetType());                                                                        
                    var strWriter = new StringWriter();
                    var xmlWriter = XmlWriter.Create(strWriter);
                    ser.Serialize(xmlWriter, comp);
                    string serXml = strWriter.ToString();

Is there a way in configure XMLSerializer to create an xlm output for root such as

<lt:LibraryType ....

instead of the current

<LibraryType .....

I'm getting ?

Lets say that your library type looks like

public class Foo
{
    public int i { get; set; }
}

public class Bar
{
    public Foo Foo { get; set; }
}

then serialization should look like

var comp = new Bar {Foo = new Foo()};

var overrides = new XmlAttributeOverrides();
overrides.Add(typeof (Bar), new XmlAttributes {XmlRoot = new XmlRootAttribute {Namespace = "http://tempuri.org"}});

// in case you want to remove prefix from members
var emptyNsAttribute = new XmlAttributes();
emptyNsAttribute.XmlElements.Add(new XmlElementAttribute { Namespace = "" });
overrides.Add(typeof(Bar), "Foo", emptyNsAttribute);
// if you actual library type contains more members, then you have to list all of them


var ser = new XmlSerializer(comp.GetType(), overrides);
var strWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(strWriter);

var ns = new XmlSerializerNamespaces();
ns.Add("lt", "http://tempuri.org");
ser.Serialize(xmlWriter, comp, ns);
string serXml = strWriter.ToString();

and the output will be

<?xml version="1.0" encoding="utf-16"?><lt:Bar xmlns:lt="http://tempuri.org"><Foo><i>0</i></Foo></lt:Bar>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM