1

I have an auto generated proxy class which contains field XmlElement[] Any. In the protocol specification a variety of other types are allowed. How would I initialize this field?

I might have, for example, something like:

 Any = new XmlElement[1]; Any[0] = new SomeRequestType().AsXmlElement() 

How would I make room for AsXmlElement in my code?

public partial class AppDataType { private System.Xml.XmlElement[] anyField; private System.Xml.XmlAttribute[] anyAttrField; /// <remarks/> [System.Xml.Serialization.XmlAnyElementAttribute(Order=0)] public System.Xml.XmlElement[] Any { get { return this.anyField; } set { this.anyField = value; } } 
1

1 Answer 1

0

To serialize directly from and to an XmlElement, you can use:

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

And then use it like:

 var appDataType = new AppDataType { Any = new[] { someRequestType.AsXmlElement() }, }; 

Prototype fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.