在C#中填充Web服务上的任何元素

时间:2017-02-08 13:32:10

标签: c# .net xml web-services

有人能指出我的C#示例,他们填充请求并接收Web服务的响应,其中架构主要是作为任何元素实现的吗?

我已经为我的项目添加了一个Web服务引用。 Web服务的WSDL /模式将服务请求和响应的大部分内容作为“任何”服务。元件。我知道基于在Java中使用此Web服务请求实现客户端的底层模式。在此先感谢您的帮助。

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);`

3 个答案:

答案 0 :(得分:2)

你的问题相当普遍,所以我要稍微缩小一下以下情况:你有一个类似[XmlAnyElement]成员的类型:

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;
        }
    }
}

您希望将Any字段初始化为以下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>

如何做到这一点?

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

首先,您可以使用代码生成工具(如http://xmltocsharp.azurewebsites.net/或Visual Studio的Paste XML as Classes)设计与所需XML相对应的c#类。然后,您可以使用XmlSerializer结合XmlDocument.CreateNavigator().AppendChild()将这些类直接序列化到XmlNode层次结构。

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

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 http://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader
    public ProperXmlNodeReader(XmlNode node)
        : base(node)
    {
    }

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

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

[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() };

示例fiddle

答案 1 :(得分:0)

XmlNode是一种抽象基类型。您可以按照XmlElement中的说明创建具体的Create New Nodes in the DOM对象并添加到Any数组中:

因此以下内容将起作用:

var dom = new XmlDocument();
var contacts = dom.CreateElement("Contacts");
dom.AppendChild(contacts);
var contact = dom.CreateElement("Contact");
contacts.AppendChild(contact);
var name = dom.CreateElement("Name");
contact.AppendChild(name);
name.InnerText = "Patrick Hines";
var phone = dom.CreateElement("Phone");
contact.AppendChild(phone);
phone.InnerText = "206-555-0144";
var address = dom.CreateElement("Address");
contact.AppendChild(address);
var street1 = dom.CreateElement("Street1");
address.AppendChild(street1);
street1.InnerText = "123 Main St";
var city = dom.CreateElement("City");
address.AppendChild(city);
city.InnerText = "Mercer Island";
var state = dom.CreateElement("State");
address.AppendChild(state);
state.InnerText = "WA";
var postal = dom.CreateElement("Postal");
address.AppendChild(postal);
postal.InnerText = "68042";

var genericRequest = new GenericRequestData_Type();
genericRequest.Any = new[] { dom.DocumentElement };

示例fiddle

答案 2 :(得分:0)

XmlNode是旧XML Document Object Model中的一种类型,可以追溯到c#1.1。它已被更容易使用的LINQ to XML对象模型所取代。不为人所知的是[XmlAnyAttribute]实际上支持这个API。因此,在您的GenericRequestData_Type类型中,您可以手动将Any属性更改为System.Xml.Linq.XElement[]类型:

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

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

然后,您可以按照Creating XML Trees in C# (LINQ to XML)

中的说明轻松地按如下方式初始化数组
// Taken from 
// https://msdn.microsoft.com/en-us/library/mt693096.aspx
var contacts =
    new XElement("Contacts",
        new XElement("Contact",
            new XElement("Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),
            new XElement("Address",
                new XElement("Street1", "123 Main St"),
                new XElement("City", "Mercer Island"),
                new XElement("State", "WA"),
                new XElement("Postal", "68042")
            )
        )
    );

var genericRequest = new GenericRequestData_Type();
genericRequest.Any = new[] { contacts };

示例fiddle