开发者

How to add namespace dynamically and xml serialization

开发者 https://www.devze.com 2023-03-03 04:33 出处:网络
my class code as public class OpenShipments { private string _xmlns = \"\"; private OpenShipment _OpenShipment = null;

my class code as

public class OpenShipments
{
    private string _xmlns = "";
    private OpenShipment _OpenShipment = null;

    [XmlAttribute("xmlns")]
    public string xmlns
    {
        get { return _xmlns; }
        set { _xmlns = "x-schema:" + value; }
    }

    [XmlElement("OpenShipment")]
    public OpenShipment OpenShi开发者_如何学Pythonpment
    {
        get { return _OpenShipment; }
        set { _OpenShipment = value; }
    }

    public OpenShipments()
    {
        _OpenShipment = new OpenShipment();
    }
}

I include a property called public string xmlns which will have namespace after serializing the code, but no namespace is added when we see the xml.

In my case i need to add namespace dynamically to OpenShipments element whose value will be dynamically set. In my case namespace will look like xmlns="x-schema:C:\UPSLabel\OpenShipments.xdr" and sometime will look like xmlns="x-schema:d:\UPSLabel\OpenShipments.xdr".

So the namespace value x-schema:d:\UPSLabel\OpenShipments.xdr will differ based on condition. I need advice how to add namespace dynamically to handle the situation.


You can do it this way:

when serialzing your class

        System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(<my class>.GetType());
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

        if(<condition>)
        {
        ns.Add(string.Empty, @"x-schema:C:\UPSLabel\OpenShipments.xdr");
        } 
        else
        {
        ns.Add(string.Empty, @"x-schema:D:\UPSLabel\OpenShipments.xdr");
        }

        xs.Serialize(<stream>, <your class instance>,ns);
0

精彩评论

暂无评论...
验证码 换一张
取 消