具有多个命名空间的 DataContractSerializer

发布于 2024-08-10 23:57:44 字数 893 浏览 5 评论 0原文

我正在使用 DataContractSerializer 将对象序列化为 XML。主要对象是 SecurityHolding,其命名空间为“http://personaltrading.test.com/”,并包含一个属性名为 Amount 的类,其命名空间为“http://core.test.com”。当我将其序列化为 XML 时,我得到以下信息:

<ArrayOfSecurityHolding xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://personaltrading.test.com/">
  <SecurityHolding>
    <Amount xmlns:d3p1="http://core.test.com/">
        <d3p1:Amount>1.05</d3p1:Amount>
        <d3p1:CurrencyCode>USD</d3p1:CurrencyCode>
    </Amount>
    <BrokerageID>0</BrokerageID>
    <BrokerageName i:nil="true" />
    <RecordID>3681</RecordID>
  </SecurityHolding></ArrayOfSecurityHolding>

我可以控制 d3p1 前缀吗?我是否做错了什么或者我应该做其他事情?

I am using a DataContractSerializer to serialize an object to XML. The main object is SecurityHolding with the namespace "http://personaltrading.test.com/" and contains a property called Amount that's a class with the namespace "http://core.test.com". When I serialize this to XML I get the following:

<ArrayOfSecurityHolding xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://personaltrading.test.com/">
  <SecurityHolding>
    <Amount xmlns:d3p1="http://core.test.com/">
        <d3p1:Amount>1.05</d3p1:Amount>
        <d3p1:CurrencyCode>USD</d3p1:CurrencyCode>
    </Amount>
    <BrokerageID>0</BrokerageID>
    <BrokerageName i:nil="true" />
    <RecordID>3681</RecordID>
  </SecurityHolding></ArrayOfSecurityHolding>

Is there anyway I can control the d3p1 prefix? Am I doing something wrong or should I be doing something else?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

隐诗 2024-08-17 23:57:45

我也曾为这个问题苦苦挣扎。我在下面提出的解决方案不是最佳的恕我直言,但它有效。就像上面的 Marc Gravell 一样,我建议使用 XmlSerializer。

诀窍是向您的类添加一个返回 XmlSerializerNamespaces 对象的字段。该字段必须用 XmlNamespaceDeclarations 属性修饰。在类的构造函数中,添加命名空间,如下例所示。在下面的 xml 中,请注意根元素以及 someString 元素的前缀正确。

有关 XmlSerializerNamespace 的详细信息

架构参考

[XmlRoot(Namespace="http://STPMonitor.myDomain.com")]
public class CFMessage : IQueueMessage<CFQueueItem>
{
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces xmlns;

    [XmlAttribute("schemaLocation", Namespace=System.Xml.Schema.XmlSchema.InstanceNamespace)]
    public string schemaLocation = "http://STPMonitor.myDomain.com/schemas/CFMessage.xsd";

    [XmlAttribute("type")]
    public string Type { get; set; }

    [XmlAttribute("username")]
    public string UserName { get; set; }

    [XmlAttribute("somestring", Namespace = "http://someURI.com")]
    public string SomeString = "Hello World";


    public List<CFQueueItem> QueueItems { get; set; }

    public CFMessage()
    {
        xmlns = new XmlSerializerNamespaces();
        xmlns.Add("myDomain", "http://STPMonitor.myDomain.com");
        xmlns.Add("xyz", "http://someURI.com");
    }
}


<?xml version="1.0" encoding="utf-16"?>
<myDomain:CFMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xyz="http://someURI.com"
xsi:schemaLocation="http://STPMonitor.myDomain.com/schemas/CFMessage.xsd"
xyz:somestring="Hello World" type="JOIN" username="SJ-3-3008-1"
xmlns:myDomain="http://STPMonitor.myDomain.com" />

I have struggled with this problem also. The solution I present below is not optimal IMHO but it works. Like Marc Gravell above, I suggest using XmlSerializer.

The trick is to add a field to your class that returns a XmlSerializerNamespaces object. This field must be decorated with a XmlNamespaceDeclarations attribute. In the constructor of your class, add namespaces as shown in the example below. In the xml below note that the root element is prefixed correctly as well as the someString element.

More info on XmlSerializerNamespaces

Schemas reference

[XmlRoot(Namespace="http://STPMonitor.myDomain.com")]
public class CFMessage : IQueueMessage<CFQueueItem>
{
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces xmlns;

    [XmlAttribute("schemaLocation", Namespace=System.Xml.Schema.XmlSchema.InstanceNamespace)]
    public string schemaLocation = "http://STPMonitor.myDomain.com/schemas/CFMessage.xsd";

    [XmlAttribute("type")]
    public string Type { get; set; }

    [XmlAttribute("username")]
    public string UserName { get; set; }

    [XmlAttribute("somestring", Namespace = "http://someURI.com")]
    public string SomeString = "Hello World";


    public List<CFQueueItem> QueueItems { get; set; }

    public CFMessage()
    {
        xmlns = new XmlSerializerNamespaces();
        xmlns.Add("myDomain", "http://STPMonitor.myDomain.com");
        xmlns.Add("xyz", "http://someURI.com");
    }
}


<?xml version="1.0" encoding="utf-16"?>
<myDomain:CFMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xyz="http://someURI.com"
xsi:schemaLocation="http://STPMonitor.myDomain.com/schemas/CFMessage.xsd"
xyz:somestring="Hello World" type="JOIN" username="SJ-3-3008-1"
xmlns:myDomain="http://STPMonitor.myDomain.com" />
兔小萌 2024-08-17 23:57:45

添加“http://www.w3.org/2001/XMLSchema”命名空间:

    private static string DataContractSerialize(object obj)
    {
        StringWriter sw = new StringWriter();

        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());

        using (XmlTextWriter xw = new XmlTextWriter(sw))
        {
            //serializer.WriteObject(xw, obj);
            //
            // Insert namespace for C# types
            serializer.WriteStartObject(xw, obj);
            xw.WriteAttributeString("xmlns", "x", null, "http://www.w3.org/2001/XMLSchema");
            serializer.WriteObjectContent(xw, obj);
            serializer.WriteEndObject(xw);
        }

        StringBuilder buffer = sw.GetStringBuilder();

        return buffer.ToString();
    }

Add "http://www.w3.org/2001/XMLSchema" namespace by:

    private static string DataContractSerialize(object obj)
    {
        StringWriter sw = new StringWriter();

        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());

        using (XmlTextWriter xw = new XmlTextWriter(sw))
        {
            //serializer.WriteObject(xw, obj);
            //
            // Insert namespace for C# types
            serializer.WriteStartObject(xw, obj);
            xw.WriteAttributeString("xmlns", "x", null, "http://www.w3.org/2001/XMLSchema");
            serializer.WriteObjectContent(xw, obj);
            serializer.WriteEndObject(xw);
        }

        StringBuilder buffer = sw.GetStringBuilder();

        return buffer.ToString();
    }
孤蝉 2024-08-17 23:57:44

首先,命名空间别名的选择对于格式良好的解析器应该没有影响。

但;它必须是 DataContractSerializer 吗?通过 XmlSerializer,您可以使用接受 XmlSerializerNamespacesSerialize 重载。这允许您选择您使用的名称空间和别名。

最终; DataContractSerializer旨在提供完整的 xml 控制;这不是它的目标。如果您想要严格的 xml 控制,XmlSerializer 是更好的选择,即使它较旧(并且有自己的一些细微差别/缺点)。

完整示例:

using System;
using System.Xml.Serialization;
public class Amount
{
    public const string CoreNamespace = "http://core.test.com/";
    [XmlElement("Amount", Namespace=CoreNamespace)]
    public decimal Value { get; set; }
    [XmlElement("CurrencyCode", Namespace = CoreNamespace)]
    public string Currency { get; set; }
}
[XmlType("SecurityHolding", Namespace = SecurityHolding.TradingNamespace)]
public class SecurityHolding
{
    public const string TradingNamespace = "http://personaltrading.test.com/";

    [XmlElement("Amount", Namespace = Amount.CoreNamespace)]
    public Amount Amount { get; set; }

    public int BrokerageId { get; set; }
    public string BrokerageName { get; set; }
    public int RecordId { get; set; }
}
static class Program
{
    static void Main()
    {
        var data = new[] {
            new SecurityHolding {
                Amount = new Amount {
                    Value = 1.05M,
                    Currency = "USD"
                },
                BrokerageId = 0,
                BrokerageName = null,
                RecordId = 3681
            }
        };
        var ser = new XmlSerializer(data.GetType(),
            new XmlRootAttribute("ArrayOfSecurityHolding") { Namespace = SecurityHolding.TradingNamespace});
        var ns = new XmlSerializerNamespaces();
        ns.Add("foo", Amount.CoreNamespace);
        ser.Serialize(Console.Out, data, ns);
    }
}

输出:

<ArrayOfSecurityHolding xmlns:foo="http://core.test.com/" xmlns="http://personaltrading.test.com/">
  <SecurityHolding>
    <foo:Amount>
      <foo:Amount>1.05</foo:Amount>
      <foo:CurrencyCode>USD</foo:CurrencyCode>
    </foo:Amount>
    <BrokerageId>0</BrokerageId>
    <RecordId>3681</RecordId>
  </SecurityHolding>
</ArrayOfSecurityHolding>

Firstly, the choice of namespace alias should make no difference to a well-formed parser.

But; does it have to be DataContractSerializer? With XmlSerializer, you can use the overload of Serialize that accepts a XmlSerializerNamespaces. This allows you to pick and choose the namespaces and aliases that you use.

Ultimately; DataContractSerializer is not intended to give full xml control; that isn't its aim. If you want strict xml control, XmlSerializer is a better choice, even if it is older (and has some nuances/foibles of its own).

Full example:

using System;
using System.Xml.Serialization;
public class Amount
{
    public const string CoreNamespace = "http://core.test.com/";
    [XmlElement("Amount", Namespace=CoreNamespace)]
    public decimal Value { get; set; }
    [XmlElement("CurrencyCode", Namespace = CoreNamespace)]
    public string Currency { get; set; }
}
[XmlType("SecurityHolding", Namespace = SecurityHolding.TradingNamespace)]
public class SecurityHolding
{
    public const string TradingNamespace = "http://personaltrading.test.com/";

    [XmlElement("Amount", Namespace = Amount.CoreNamespace)]
    public Amount Amount { get; set; }

    public int BrokerageId { get; set; }
    public string BrokerageName { get; set; }
    public int RecordId { get; set; }
}
static class Program
{
    static void Main()
    {
        var data = new[] {
            new SecurityHolding {
                Amount = new Amount {
                    Value = 1.05M,
                    Currency = "USD"
                },
                BrokerageId = 0,
                BrokerageName = null,
                RecordId = 3681
            }
        };
        var ser = new XmlSerializer(data.GetType(),
            new XmlRootAttribute("ArrayOfSecurityHolding") { Namespace = SecurityHolding.TradingNamespace});
        var ns = new XmlSerializerNamespaces();
        ns.Add("foo", Amount.CoreNamespace);
        ser.Serialize(Console.Out, data, ns);
    }
}

Output:

<ArrayOfSecurityHolding xmlns:foo="http://core.test.com/" xmlns="http://personaltrading.test.com/">
  <SecurityHolding>
    <foo:Amount>
      <foo:Amount>1.05</foo:Amount>
      <foo:CurrencyCode>USD</foo:CurrencyCode>
    </foo:Amount>
    <BrokerageId>0</BrokerageId>
    <RecordId>3681</RecordId>
  </SecurityHolding>
</ArrayOfSecurityHolding>
南薇 2024-08-17 23:57:44

我解决这个问题的方法与 Marc 略有不同,可以在基类中实现。

  1. 创建一个新属性来定义您将在数据协定中使用的其他 XML 命名空间。

    [AttributeUsage(AttributeTargets.Class,Inherited = true,AllowMultiple = true)]    
    公共密封类 NamespaceAttribute :属性    
    {   
    
        公共命名空间属性()
        {
        }
    
        public NamespaceAttribute(字符串前缀,字符串uri)
        {
            前缀=前缀;
            乌里 = 乌里;
        }
    
        公共字符串前缀 { get;放; }
        公共字符串 Uri { 获取;放; }
    }
    
  2. 将该属性添加到您的数据契约中。

    [DataContract(Name = "SomeObject", Namespace = "http://schemas.domain.com/namespace/")]    
    [命名空间(前缀=“a”,Uri=“http://schemas.microsoft.com/2003/10/Serialization/Arrays”)]    
    [命名空间(前缀=“wm”,Uri=“http://schemas.datacontract.org/2004/07/System.Windows.Media”)]           
    公共类 SomeObject : SerializedObject          
    {    
    
        私有 IList<颜色>颜色;
    
        [数据成员]
        [显示名称(“颜色”)]
        公共 IList<颜色>颜色
        {
            获取{返回颜色; }
            设置{颜色=值; }
        }
    }
    
  3. 然后在您的 Save 方法中,使用反射来获取属性,然后将它们写入文件。

    public static void Save(SerializedObject o, 字符串文件名)
    {
        使用 (Stream outputStream = new FileStream(文件名, FileMode.Create, FileAccess.Write))
        {
            如果(输出流==空)
                throw new ArgumentNullException(“必须有有效的输出流”);
    
            if (outputStream.CanWrite == false)
                throw new ArgumentException("无法写入输出流");
    
            对象[]属性;
            属性 = o.GetType().GetCustomAttributes(typeof(NamespaceAttribute), true);    
    
            XmlWriterSettings writerSettings = new XmlWriterSettings();                
            writerSettings.Indent = true;
            writerSettings.NewLineOnAttributes = true;                
            使用 (XmlWriter w = XmlWriter.Create(outputStream, writerSettings))
            {
                DataContractSerializer s = new DataContractSerializer(o.GetType());
    
                s.WriteStartObject(w, o);
                foreach(属性中的NamespaceAttribute ns)                      
                    w.WriteAttributeString("xmlns", ns.Prefix, null, ns.Uri);
    
                // 内容
                s.WriteObjectContent(w, o);
                s.WriteEndObject(w);
            }
        }
    }
    

I have solved this problem slightly differently to Marc that can be implemented in a base class.

  1. Create a new attribute to define the additional XML namespaces that you will use in your data contract.

    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]    
    public sealed class NamespaceAttribute : Attribute    
    {   
    
        public NamespaceAttribute()
        {
        }
    
        public NamespaceAttribute(string prefix, string uri)
        {
            Prefix = prefix;
            Uri = uri;
        }
    
        public string Prefix { get; set; }
        public string Uri { get; set; }
    }
    
  2. Add the attribute to your data contracts.

    [DataContract(Name = "SomeObject", Namespace = "http://schemas.domain.com/namespace/")]    
    [Namespace(Prefix = "a", Uri = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]    
    [Namespace(Prefix = "wm", Uri = "http://schemas.datacontract.org/2004/07/System.Windows.Media")]           
    public class SomeObject : SerializableObject          
    {    
    
        private IList<Color> colors;
    
        [DataMember]
        [DisplayName("Colors")]
        public IList<Colors> Colors
        {
            get { return colors; }
            set { colours = value; }
        }
    }
    
  3. Then in your Save method, use reflection to get the attributes and then write them to the file.

    public static void Save(SerializableObject o, string filename)
    {
        using (Stream outputStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
        {
            if (outputStream == null)
                throw new ArgumentNullException("Must have valid output stream");
    
            if (outputStream.CanWrite == false)
                throw new ArgumentException("Cannot write to output stream");
    
            object[] attributes;
            attributes = o.GetType().GetCustomAttributes(typeof(NamespaceAttribute), true);    
    
            XmlWriterSettings writerSettings = new XmlWriterSettings();                
            writerSettings.Indent = true;
            writerSettings.NewLineOnAttributes = true;                
            using (XmlWriter w = XmlWriter.Create(outputStream, writerSettings))
            {
                DataContractSerializer s = new DataContractSerializer(o.GetType());
    
                s.WriteStartObject(w, o);
                foreach (NamespaceAttribute ns in attributes)                      
                    w.WriteAttributeString("xmlns", ns.Prefix, null, ns.Uri);
    
                // content
                s.WriteObjectContent(w, o);
                s.WriteEndObject(w);
            }
        }
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文