Populating ANY elements on a web service in C#

后端 未结 3 1457
误落风尘
误落风尘 2020-12-21 04:42

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?

3条回答
  •  不知归路
    2020-12-21 05:28

    XmlNode is a type in the old XML Document Object Model that dates from c# 1.1. It has been superseded by the much easier to use LINQ to XML object model. What is not well known is that [XmlAnyElementAttribute] actually supports this API. Thus in your GenericRequestData_Type type you could manually change the Any property to be of type 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;
            }
        }
    }
    

    Then you can initialize the array easily as follows, following the instructions in 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 };
    

    Sample fiddle.

提交回复
热议问题