如何在xml序列化时添加名称空间

本文关键字:添加 空间 序列化 xml | 更新日期: 2023-09-27 17:54:58

            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();

没有找到错误对象引用,因为我以编程方式添加了名称空间。在我的XML命名空间中应该是

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

这里我添加ns.Add("x-schema:", @"x-schema:C:'UPSLabel'OpenShipments.xdr");

一行

和上面的行,我得到错误....我错在哪里?只是想不出来。请帮我构造命名空间

如何在xml序列化时添加名称空间

试试:

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();
}

将生成:

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

一行:

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

添加了一个别名,即允许序列化器在xml中使用x-schema:。然而,这并不会使你的对象使用这个命名空间;为此,您需要(在您的类型上):

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

(或类似的东西,可能使用XmlAttributeOverrides)

注意,加上别名,您将得到:

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

要获得不带别名的名称,您需要:

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

输出:

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