2015-03-13 117 views
0

我想同时使用的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 

回答

2

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

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

希望它能起作用。它为我工作。

+0

这正是我正在寻找的。非常感谢! – Undercover1989 2015-03-13 16:34:14

0

编辑:这种解决方案,这只能帮助单向。如果我想用我的类反序列化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);