如何从.net framework1.1中的Web服务的xml输出中删除xmlns:XSI和xmlns:XSD命名空间

时间:2010-04-19 11:58:57

标签: .net web-services

HI, 这是一个老问题,我在这个论坛上已经看到了一些解决方案,但我第一次尝试使用网络服务,所以请耐心等待。

我有一个以下列格式返回XML的Web服务

<subs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" msisdn="965xxxxxx">
<shortcode label="XXXX">
<channels>
<channel>
<id>442</id>
<name>News</name>
<billingperiod>7</billingperiod>
<billingamount>3</billingamount>
<lastbilling>4/14/2010 1:41:11 PM</lastbilling>
</channel>
<channel>
<id>443</id>
<name>News2</name>
<billingperiod>7</billingperiod>
<billingamount>3</billingamount>
<lastbilling>4/14/2010 1:41:19 PM</lastbilling>
</channel>
</channels>
</shortcode>
</subs>

我想要没有xmlns:xsd和xmlns:xsi标签的相同XMl输出。

我尝试了以下建议的解决方案:

  <WebMethod(MessageName:="GetSubscription")> 
  Public Function GetSubscription(....) As String

  Dim namespaces As New XmlSerializerNamespaces
  namespaces.Add(String.Empty, String.Empty)

  Dim serializer As New XmlSerializer(SubsDetail.GetType)
  Dim sw As New System.IO.StringWriter
  Dim writer As New System.Xml.XmlTextWriter(sw)
  writer.Formatting = Formatting.None
  serializer.Serialize(writer, SubsDetail, namespaces)
  writer.Close()
  Return sw.toString()

结果是我得到了一个xml,格式如下:

<string>
<?xml version="1.0" encoding="utf-16"?><subs msisdn="965xxxx">
    <shortcode label="XXXX">
    <channels>
    <channel>
    <id>442</id>
    <name>News</name>
    <billingperiod>7</billingperiod>
    <billingamount>3</billingamount>
    <lastbilling>4/14/2010 1:41:11 PM</lastbilling>
    </channel>
    <channel>
    <id>443</id>
    <name>News2</name>
    <billingperiod>7</billingperiod>
    <billingamount>3</billingamount>
    <lastbilling>4/14/2010 1:41:19 PM</lastbilling>
    </channel>
    </channels>
    </shortcode>
    </subs>
</string>

虽然xml的格式是正确的,但它在<string>标签中以字符串形式出现。这真让我疯了。

我可以将输出作为xml而没有外部字符串标记吗?

1 个答案:

答案 0 :(得分:1)

我在这里找到了解决方案, Returning XML natively in a .NET (C#) webservice?

我没有以完全相同的方式使用它,我使用成员的属性标签对类进行序列化,然后将xml字符串加载到XMl文档中并将其返回给调用服务...

以下是代码示例:

  Dim namespaces As New XmlSerializerNamespaces
  namespaces.Add(String.Empty, String.Empty)

  Dim serializer As New XmlSerializer(SubsDetail.GetType)
  Dim sw As New System.IO.StringWriter
  Dim writer As New System.Xml.XmlTextWriter(sw)
  'writer.Formatting = Formatting.None
  serializer.Serialize(writer, SubsDetail, namespaces)
  writer.Flush()
  Dim xmlDocument As New XmlDocument
  xmlDocument.LoadXml(sw.ToString())
  Return xmlDocument

我序列化的我的Struct构造使用以下方式的Xml属性:

  <XmlRootAttribute("subs", _
 Namespace:="", IsNullable:=False)> _
  Structure Subs
    <XmlAttributeAttribute()> _
    Public msisdn As String
    <XmlElement()> _
    Public shortcode() As shortcodelist
    '<XmlNamespaceDeclarations()> _
    'Public xmlns As XmlSerializerNamespaces

  End Structure

希望这有助于某人......某个地方......有时......