下面这段xml格式是一般soap的接口所返回的格式,但实际项目中的header和body部分的根节点是需要有前缀 “ns2”,实际上只需要添加一个namespace就行,但之前没有接触过。节点类似soapenv:Envelope
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<responseHeader xmlns:ns2="http://www.org/">
<numberOfHits>2</numberOfHits>
</responseHeader>
</soap:Header>
<soap:Body>
<getItem xmlns:ns2="http://www.org/" />
</soap:Body>
</soap:Envelope>
百度是个坑,查到的结果大部分都是关于请求部分,很少有返回部分的例子,谷歌也搜了半天,最后终于找到解决办法。
下面的代码为 VB,C#可参照转换
<System.Xml.Serialization.XmlNamespaceDeclarations> _
Public Property xmlns() As XmlSerializerNamespacesGet
Dim xsn = New XmlSerializerNamespaces()
xsn.Add("ns2", "http://www.org/")
Return xsn
End Get
Set(value As XmlSerializerNamespaces)End Set
End Property
把上面这段代码添加到需要“ns2”前缀的类里边去,比如我上面的responseHeader和getItem部分:
'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929"), _
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http://www.org/")> _
Partial Public Class getItemPrivate gepirItemField() As ItemDataLineType
<System.Xml.Serialization.XmlNamespaceDeclarations> _
Public Property xmlns() As XmlSerializerNamespacesGet
Dim xsn = New XmlSerializerNamespaces()
xsn.Add("ns2", "http://www.org/")
Return xsn
End Get
Set(value As XmlSerializerNamespaces)End Set
End Property
'''<remarks/>
<System.Xml.Serialization.XmlArrayAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified), _
System.Xml.Serialization.XmlArrayItemAttribute("itemDataLine", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=False)> _
Public Property gepirItem() As ItemDataLineType()
Get
Return Me.gepirItemField
End Get
Set(value As ItemDataLineType())
Me.gepirItemField = value
End Set
End Property
End Class
最后生成的结果就行想要的了,xml添加了指定的前缀
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<ns2:responseHeader xmlns:ns2="http://www.org/">
<numberOfHits>2</numberOfHits>
</ns2:responseHeader>
</soap:Header>
<soap:Body>
<ns2:getItem xmlns:ns2="http://www.org/" />
</soap:Body>
</soap:Envelope>