C# - 如何控制XML序列化的格式?

时间:2015-08-03 14:04:21

标签: c# xml

我有一个类需要序列化为XML,并且具有我正在使用的WCF服务的特定格式。 类结构是这样的:

[XmlRoot(Namespace="http://schemas.datacontract.org/2004/07/XXX.IT.Messaging.Common.Entities")]
public class PushBroadcastingParams
{
    [XmlElement]
    public string appId { get; set; }

    [XmlElement]
    public string message { get; set; }

    [XmlArray(Namespace = "http://schemas.datacontract.org/2004/07/XXX.IT.Messaging.Common.Entities.KMS.Requests")]
    public List<CustomKeyValuePair> customData { get; set; }
}

[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/XXX.IT.Messaging.Common.Entities")]
public class PushNotificationParams : PushBroadcastingParams
{
    [XmlArray(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
    public string[] subscribersIDs { get; set; }
}

这是我的序列化代码:

public static string SerializeXML<T>(T obj, XmlSerializerNamespaces namespaces = null)
{
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");
    using (StringWriter sw = new StringWriter())
    {
        using (XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true }))
        {
            new XmlSerializer(typeof(T)).Serialize(writer, obj, ns);

            return sw.ToString();
        }
    }
}

我需要XML输出完全如下:

<PushNotificationParams xmlns="http://schemas.datacontract.org/2004/07/XXX.IT.Messaging.Common.Entities" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <appId>123</appId>
  <customData xmlns:orb="http://schemas.datacontract.org/2004/07/XXX.IT.Messaging.Common.Entities.KMS.Requests">
    <orb:CustomKeyValuePair>
      <orb:Key>HEADER</orb:Key>
      <orb:Value>FOCUS</orb:Value>
    </orb:CustomKeyValuePair>
    <orb:CustomKeyValuePair>
      <orb:Key>TITLE</orb:Key>
      <orb:Value>title of message</orb:Value>
    </orb:CustomKeyValuePair>
    <orb:CustomKeyValuePair>
      <orb:Key>DESC</orb:Key>
      <orb:Value>desc of message</orb:Value>
    </orb:CustomKeyValuePair>
    <orb:CustomKeyValuePair>
      <orb:Key>MESSAGE_TYPE</orb:Key>
      <orb:Value>POD</orb:Value>
    </orb:CustomKeyValuePair>
  </customData>
  <message>test</message>
  <subscribersIDs xmlns:orb="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <orb:string>USER-NAME</orb:string>
  </subscribersIDs>
</PushNotificationParams>

但我无法使用名称空间和前缀这样的前缀,我无法摆脱xmlns:xsd命名空间。

0 个答案:

没有答案
相关问题