在C#中填充Web服务上的任何元素 [英] Populating ANY elements on a web service in C#

查看:56
本文介绍了在C#中填充Web服务上的任何元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我指出一个C#示例,在该示例中,他们填充一个请求并接收对该Web服务的响应,该Web服务中的模式主要实现为ANY元素?

Can someone point me to a C# example where they populate a request and receive the response for a web service where the schema is mostly implemented as ANY elements?

我已将Web服务引用添加到我的项目中。 Web服务的WSDL /模式将服务请求和响应的大部分内容作为 ANY元素。我知道基于Java实现此Web服务请求的客户端的基础架构。在此先感谢您的帮助。

I have added a web service reference to my project. The WSDL/schema for the web service has most of the body of the service request and response as an 'ANY' element. I know the underlying schema based on implementing a client to this web service request in Java. Thanks in advance for help.

ServiceGenericRequest_Type requestBody = <init>
GenericRequestData_Type genericRequest = <init>;

// here is where the ANY element starts
genericRequest.Any = new System.Xml.XmlElement[1];

// receive error that I can not create abstract type
System.Xml.XmlNode inqNode = new System.Xml.XmlNode();

genericRequest.Any[0].AppendChild(inqNode);`


推荐答案

您的问题相当笼统,因此我将其范围缩小到以下情况:您的类型为 [XmlAnyElement] 成员如下:

Your question is fairly general so I'm going to narrow it down a bit to the following situation: you have a type with an [XmlAnyElement] member like so:

public class GenericRequestData_Type
{
    private System.Xml.XmlElement[] anyField;

    [System.Xml.Serialization.XmlAnyElementAttribute()]
    public System.Xml.XmlElement[] Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}

您想初始化任何字段到以下XML:

And you would like to initialize the Any field to the following XML:

<Contacts>
  <Contact>
    <Name>Patrick Hines</Name>
    <Phone>206-555-0144</Phone>
    <Address>
      <Street1>123 Main St</Street1>
      <City>Mercer Island</City>
      <State>WA</State>
      <Postal>68042</Postal>
    </Address>
  </Contact>
</Contacts>

这怎么办?

有几种选择,所以我将其分解为几个不同的答案。

There are several options, so I'll break it down into a few different answers.

首先,您可以使用代码生成工具(例如 http://xmltocsharp.azurewebsites.net)设计与所需XML相对应的c#类。 / 或Visual Studio的将XML粘贴为类。然后,您可以使用XmlNode 层次结构。 serialization.xmlserializer.aspx rel = nofollow noreferrer> XmlSerializer XmlDocument.CreateNavigator()。AppendChild()

Firstly, you could design c# classes corresponding to your desired XML using a code-generation tool such as http://xmltocsharp.azurewebsites.net/ or Visual Studio's Paste XML as Classes. Then you can serialize those classes directly to an XmlNode hierarchy using XmlSerializer combined with XmlDocument.CreateNavigator().AppendChild().

首先,介绍以下扩展方法:

First, introduce the following extension methods:

public static class XmlNodeExtensions
{
    public static XmlDocument AsXmlDocument<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
    {
        XmlDocument doc = new XmlDocument();
        using (XmlWriter writer = doc.CreateNavigator().AppendChild())
            new XmlSerializer(o.GetType()).Serialize(writer, o, ns ?? NoStandardXmlNamespaces());
        return doc;
    }

    public static XmlElement AsXmlElement<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
    {
        return o.AsXmlDocument(ns, serializer).DocumentElement;
    }

    public static T Deserialize<T>(this XmlElement element, XmlSerializer serializer = null)
    {
        using (var reader = new ProperXmlNodeReader(element))
            return (T)(serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
    }

    /// <summary>
    /// Return an XmlSerializerNamespaces that disables the default xmlns:xsi and xmlns:xsd lines.
    /// </summary>
    /// <returns></returns>
    public static XmlSerializerNamespaces NoStandardXmlNamespaces()
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
        return ns;
    }
}

public class ProperXmlNodeReader : XmlNodeReader
{
    // Bug fix from this answer https://stackoverflow.com/a/30115691/3744182
    // To http://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader
    // By https://stackoverflow.com/users/8799/nathan-baulch
    public ProperXmlNodeReader(XmlNode node) : base(node) { }

    public override string LookupNamespace(string prefix)
    {
        return NameTable.Add(base.LookupNamespace(prefix));
    }
}

接下来,定义与您的<$ c $相对应的类型c>< Contacts> 层次结构:

Next, define types corresponding to your <Contacts> hierarchy:

[XmlRoot(ElementName = "Address")]
public class Address
{
    [XmlElement(ElementName = "Street1")]
    public string Street1 { get; set; }
    [XmlElement(ElementName = "City")]
    public string City { get; set; }
    [XmlElement(ElementName = "State")]
    public string State { get; set; }
    [XmlElement(ElementName = "Postal")]
    public string Postal { get; set; }
}

[XmlRoot(ElementName = "Contact")]
public class Contact
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }
    [XmlElement(ElementName = "Phone")]
    public string Phone { get; set; }
    [XmlElement(ElementName = "Address")]
    public Address Address { get; set; }
}

[XmlRoot(ElementName = "Contacts")]
public class Contacts
{
    [XmlElement(ElementName = "Contact")]
    public Contact Contact { get; set; }
}

[XmlRoot("GenericRequestData_Type")]
public class Person
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
    [XmlArray("Emails")]
    [XmlArrayItem("Email")]
    public List<string> Emails { get; set; }
    [XmlArray("Issues")]
    [XmlArrayItem("Id")]
    public List<long> IssueIds { get; set; }
}

最后,初始化 GenericRequestData_Type 如下:

var genericRequest = new GenericRequestData_Type();

var contacts = new Contacts
{
    Contact = new Contact
    {
        Name = "Patrick Hines",
        Phone = "206-555-0144",
        Address = new Address
        {
            Street1 = "123 Main St",
            City = "Mercer Island",
            State = "WA",
            Postal = "68042",
        },
    }
};
genericRequest.Any = new[] { contacts.AsXmlElement() };

样本小提琴

这篇关于在C#中填充Web服务上的任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆