【问题标题】:Serialize root element in a namespace, not without a namespace序列化命名空间中的根元素,而不是没有命名空间
【发布时间】:2015-03-13 11:59:48
【问题描述】:

我想在使用 XmlSerializer 时获取以下 XML:

<?xml version="1.0"?>
<GetProfileRequest xmlns="urn:veloconnect:profile-1.1">
</GetProfileRequest>

但是当我序列化时,我得到以下 XML:

<?xml version="1.0"?>
<GetProfileRequest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</GetProfileRequest>

序列化代码:

GetProfileRequest request = new GetProfileRequest();

XmlSerializer serialize = new XmlSerializer(typeof(GetProfileRequest));
serialize.Serialize(Response.OutputStream, request);

类:

[System.Xml.Serialization.XmlIncludeAttribute(typeof(TransactionRequestType))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:veloconnect:profile-1.1")]
public partial class GetProfileRequest : RequestType
{
}

[System.Xml.Serialization.XmlIncludeAttribute(typeof(TransactionRequestType))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:veloconnect:transaction-1.0")]
public partial class RequestType
{
}

是否有可以在“GetProfileRequest”类中​​定义的属性或有助于将 xmlns="urn:veloconnect:profile-1.1" 命名空间引入 XML 的属性?

我还尝试通过以下代码手动添加 XmlSerializeNamespace,但这只是删除了根元素中的所有命名空间声明,而不是创建所需的声明。

 XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
 ns.Add("", "urn:veloconnect:profile-1.1");
 // and then call serialize.Serialize with ns

【问题讨论】:

    标签: c# xml xsd


    【解决方案1】:

    您缺少一行代码。 在您的类中添加以下代码。

    **[System.Xml.Serialization.XmlRoot("GetProfileRequest", Namespace = "urn:veloconnect:profile-1.1", IsNullable = false)**]
    

    希望它会奏效。它对我有用。

    【讨论】:

    • 这正是我正在寻找的。非常感谢!
    【解决方案2】:

    编辑:此解决方案仅有助于单向。如果我想用我的类反序列化 XML,它不起作用。

    好吧,我能够尝试运行 XmlSerializeNamespace。我比我想象的更接近。这不是一个干净的解决方案,因为它是从序列化程序而不是类本身处理的。但总比没有解决好。如果有人有更好的解决方案,我将不胜感激。

    string sDefaultNamespace = "urn:veloconnect:profile-1.1";
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", sDefaultNamespace);
    
    XmlSerializer serialize = new XmlSerializer(ResponseResult.GetType(), sDefaultNamespace);
    serialize.Serialize(Response.OutputStream, ResponseResult, ns);
    

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多