开发者

How to add namespace at the time of xml serialization

            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);
            XmlSerializer serializer = new XmlSerializer(typeof(OpenShipments));
            var ns = new XmlSerializerNamespaces();
            ns.Add("x-schema:", @"x-schema:C:\UPSLabel\OpenShipments.xdr");
            serializer.Serialize(writer, OS, ns);
            xmlString = sb.ToString();

getting error object reference not found because i add namespace programatically. basically in my xml namespace will look like below one

<OpenShipments xmlns="x-schema:C:\UPSLabe开发者_开发问答l\OpenShipments.xdr">

here i add the line ns.Add("x-schema:", @"x-schema:C:\UPSLabel\OpenShipments.xdr");

and for the above line i am getting error....what is my mistake. just can not figure out. please help me to construct the namespace.


Try like this:

var sb = new StringBuilder();
var myns = @"x-schema:C:\UPSLabel\OpenShipments.xdr";
using (var writer = XmlWriter.Create(sb))
{
    var serializer = new XmlSerializer(typeof(OpenShipments), myns);
    var ns = new XmlSerializerNamespaces();
    ns.Add(string.Empty, myns);
    serializer.Serialize(writer, OS, ns);
    xmlString = sb.ToString();
}

will generate:

<OpenShipments xmlns="x-schema:C:\UPSLabel\OpenShipments.xdr">
    ...
</OpenShipments>


The line:

ns.Add("x-schema:", @"x-schema:C:\UPSLabel\OpenShipments.xdr");

is adding an alias, i.e. allowing the serializer to use x-schema: inside the xml. However this doesn't make your object use this namespace; for that, you need (on your type):

[XmlRoot(Namespace=@"x-schema:C:\UPSLabel\OpenShipments.xdr")]
public class OpenShipments {...}

(or something equivalent, perhaps using XmlAttributeOverrides)

Note that with the alias added, you will get:

<x-schema:OpenShipments xmlns:x-schema="x-schema:C:\UPSLabel\OpenShipments.xdr" />

To get it without an alias, you want:

ns.Add("", @"x-schema:C:\UPSLabel\OpenShipments.xdr");

which gives output:

<OpenShipments xmlns="x-schema:C:\UPSLabel\OpenShipments.xdr" />
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜