I'm logging xml object by serializing the object, I've looked at several presented solutions from here and the result is that for sub elements I still get the xmlns=. This caused an issue with the vendor I'm working with as they claimed this was the reason for a failure i was experiencing (it was not). But for future consideration I want to log the xml data we are sending exactly as the Connected service does, without the xmlns=.
This is how the Object is defined (WSDL auto gened code)
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111")]
public partial class Address : object, System.ComponentModel.INotifyPropertyChanged
{
private string fullNameField;
public Address()
{
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public string FullName
{
get
{
return this.fullNameField;
}
set
{
this.fullNameField = value;
this.RaisePropertyChanged("FullName");
}
}
}
This is the routine I'm using to serialize:
public static string SerializeObject<T>(T dataObject)
{
if (dataObject == null) return string.Empty;
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
NewLineHandling = NewLineHandling.None,
NewLineOnAttributes = false,
};
XmlAttributes xmlAttributes = new XmlAttributes { Xmlns = false };
var xmlAttributeOverrides = new XmlAttributeOverrides();
xmlAttributeOverrides.Add(dataObject.GetType(), xmlAttributes);
try
{
XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty, string.Empty) });
using (StringWriter xmlWriter = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(xmlWriter, settings))
{
var serializer = new XmlSerializer(typeof(T), xmlAttributeOverrides);
serializer.Serialize(xmlWriter, dataObject, emptyNS);
return xmlWriter.ToString();
}
}
}
catch (Exception)
{
return string.Empty;
}
}
}
And finally this is the output:
<?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
<Authenticator>Removed</Authenticator>
<Address>
<FullName xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">Test 103</FullName>
<PhoneNumber xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111" />
<FullAddress xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">
103 Linda Lane
Media PA 19063</FullAddress>
</Address>
</CleanseAddressRequest>
Based on my efforts with the vendor I want to be able to use output like:
<?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
<Authenticator>Removed</Authenticator>
<Address>
<FullName>Test 103</FullName>
<PhoneNumber />
<FullAddress>
103 Linda Lane
Media PA 19063</FullAddress>
</Address>
</CleanseAddressRequest>
The work around I used to resolve my issue was to manually edit the XML, not what is useful for future maintainers of the code base.
How can I programmatically remove the extraneous xmlns=?
Edited for spelling error.
Related
I need to remove all of the xmlns attributes from every element. I am using the XmlSerializer class in c#.
Here is a sample of the XML I am getting from serializing an object returned by a webservice.
Code for serialization
public static string ToXML<T>(object obj,string nameSpace)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var xml = "";
using (var stringwriter = new StringWriter())
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, obj,ns);
xml = xml + stringwriter;
}
return xml;
}
Calling Code
var unitInfo = RC.GetUnitInfo(txtUnitNum.Text);
var x = XML.DocumentExtensions.ToXML<Vehicles>(unitInfo, "");
Result
<Vehicles>
<Unit xmlns="http://Entities/2006/09">430160</Unit>
<VinNumber xmlns="http://Entities/2006/09">1FUJGP9337</VinNumber>
<CustName xmlns="http://Entities/2006/09">Ryder : N/A</CustName>
<CustCode xmlns="http://Entities/2006/09">4199</CustCode>
<NationalAccountFVM xmlns="http://Entities/2006/09">0</NationalAccountFVM>
<VehMake xmlns="http://Entities/2006/09">FREIGHTLINER/MERCEDES</VehMake>
<VehModel xmlns="http://Entities/2006/09">PX12564ST CASCADIA</VehModel>
<VehYear xmlns="http://Entities/2006/09">2012</VehYear>
<VehDescrip xmlns="http://Entities/2006/09">TRACTOR</VehDescrip>
<InService xmlns="http://Entities/2006/09">10/28/2011 12:00:00 AM</InService>
<EngMake xmlns="http://Entities/2006/09">CUMMINS ENGINE CO.</EngMake>
<EngModel xmlns="http://Entities/2006/09">ISX'10 14.9 450/1800</EngModel>
<EngSize xmlns="http://Entities/2006/09">450</EngSize>
<EngSerial xmlns="http://Entities/2006/09">79502</EngSerial>
<TransMake xmlns="http://Entities/2006/09">FULLER TRANS., DIV. EATON</TransMake>
</Vehicles
I need to serialize the object without getting the xmlns attributes.
Vehicle Object
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://Entities/2006/09")]
public partial class Vehicles {
private string unitField;
private string vinNumberField;
/// <remarks/>
public string Unit {
get {
return this.unitField;
}
set {
this.unitField = value;
}
}
/// <remarks/>
public string VinNumber {
get {
return this.vinNumberField;
}
set {
this.vinNumberField = value;
}
}
}
I modified your ToXML() method below to always correctly exclude a namespace.
The main difference is how the XmlSerializerNamespaces is instantiated.
Generating an empty namespace disables the inserting of namespaces by the XmlWriter into the output XML.
I also change how you build the output XML since string concatenation is more resource intensive than utilizing a StringBuilder in conjuction with a StringWriter.
public static string ToXML<T>(object obj)
{
StringBuilder outputXml = new StringBuilder();
using (var stringwriter = new StringWriter(outputXml))
{
// Define a blank/empty Namespace that will allow the generated
// XML to contain no Namespace declarations.
XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, obj, emptyNS);
}
return outputXml.ToString();
}
Passing in a sample object, I get the output XML of
<?xml version="1.0" encoding="utf-16"?>
<Vehicles>
<Unit>430160</Unit>
<VinNumber>1FUJGP9337</VinNumber>
<CustName>Ryder : N/A</CustName>
<CustCode>4199</CustCode>
<NationalAccountFVM>0</NationalAccountFVM>
<VehMake>FREIGHTLINER/MERCEDES</VehMake>
<VehModel>PX12564ST CASCADIA</VehModel>
<VehYear>2012</VehYear>
<VehDescrip>TRACTOR</VehDescrip>
<InService>2011-10-28T00:00:00</InService>
<EngMake>CUMMINS ENGINE CO.</EngMake>
<EngModel>ISX'10 14.9 450/1800</EngModel>
<EngSize>450</EngSize>
<EngSerial>79502</EngSerial>
<TransMake>FULLER TRANS., DIV. EATON</TransMake>
</Vehicles>
I want to create a serialisable class to represent an xml envelope that can contain arbitrary message content. Example xml (simplified) below:
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<MessageA>
<Url></Url>
</MessageA>
</Envelope>
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<MessageB>
<Value></Value>
</MessageB>
</Envelope>
My idea is to use a generic envelope class to handle this:
[Serializable]
[XmlRoot(ElementName="Envelope")]
public class Envelope<TContent> where TContent : new()
{
public Envelope()
{
Content = new TContent();
}
public TContent Content { get; set; }
}
[Serializable]
public class MessageA
{
public string Url { get; set; }
}
[Serializable]
public class MessageB
{
public string Value { get; set; }
}
These could be serialised so:
var envelope = new Envelope<MessageA>();
envelope.Content.Url = "http://www.contoso.com";
string xml = envelope.ToXml();
However, instead of the xml message that I want (per examples above), I get the following. How can I change the classes or the serialisation process to rename the Content element to the name of the Message itself?
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<Content>
<Url>http://www.contoso.com</Url>
</Content>
</Envelope>
Found that the XmlAttributeOverrides class has a solution for this problem. Adding the following method to the Envelope class causes the ToXml() extension method to serialise the object as required.
public string ToXml()
{
return ToXml(typeof(TContent).Name);
}
public string ToXml(string contentElementName)
{
XmlElementAttribute element = new XmlElementAttribute(contentElementName, typeof(TContent));
XmlAttributes attributes = new XmlAttributes();
attributes.XmlElements.Add(element);
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Envelope<TContent>), "Content", attributes);
return ToXml(this, overrides);
}
public string ToXml(Envelope<TContent> value, XmlAttributeOverrides overrides)
{
using (var sw = new Utf8StringWriter())
{
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = omitXmlDeclaration,
Indent = true
};
XmlSerializer xs = new XmlSerializer(typeof(Envelope<TContent>), overrides);
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
xs.Serialize(writer, value);
}
return sw.ToString();
}
}
I'm having a bit of trouble getting the desired xml serialization that I want. Thanks beforehand for your help.
So, the xml that I am aiming for looks something like this:
<ChangeSet>
<Change class="object" key="foo">
bar
</Change>
<Change class="testing" key="temp">
temp
</Change>
</ChangeSet>
What I'm actually getting is:
<ChangeSet>
<Change class="object" key="foo">
<Value> bar </Value>
</Change>
<Change class="testing" key="temp">
<Value> temp </Value>
</Change>
</ChangeSet>
Note that the value inside of the Value tags need to be able to be any object. (Collection, object, generic type... etc)
How can I get rid of the Value tags?
C# code:
[Serializable]
[XmlRoot("ChangeSet")]
public class ChangeSet
{
[XmlElement("Change", typeof(Change))]
public List<Change> Changes;
}
public class Change
{
[XmlAttribute("Class")]
public string Class;
[XmlAttribute("Description")]
public string Key;
public object Value;
}
StringBuilder xml = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(objToSerialize.GetType());
XmlWriterSettings settings = new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Indent = true
};
using (StringWriter writer = new StringWriter(xml))
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", ""); // Removes the xsd & xsi namespace declarations from the xml
serializer.Serialize(xmlWriter, objToSerialize, ns);
}
}
Use [XmlText] attribute over Value of type string
[XMLText]
public string Value;
or use another string property and ignore the Value property
[XMLIgnore]
public object Value;
[XMLText]
public string ValueString
{
get{ return this.Value.ToString(); }
}
I want to create a serializable C# class that would serialize into:
<metadata>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
<entry key="">false</entry>
</metadata>
Can you help me? I can't handle different entry node structure:/ Too hard for me:P
Let's begin from the lowest class in the hierarchy:
[Serializable]
public class DimensionInfo
{
[XmlElement("enabled")]
public Boolean Enabled { get; set; }
public DimensionInfo()
{
}
}
As you see, there's nothing special here. Then, proceed with the next:
[Serializable]
public class Entry
{
private DimensionInfo _dimensionInfo = default(DimensionInfo);
private Boolean _containsDimensionInfo = true;
[XmlAttribute("key")]
public String Key { get; set; }
[XmlText(typeof(String))]
public String ContainsDimensionInfo
{
get
{
return CheckDimensionContaining().ToString().ToLower();
}
set
{
_containsDimensionInfo = Boolean.Parse(value);
}
}
[XmlIgnore]
public Boolean ContainsDimensionInfoSpecified
{
get { return !CheckDimensionContaining(); }
}
[XmlElement("dimensionInfo")]
public DimensionInfo DimensionInfo
{
get { return _dimensionInfo; }
set { _dimensionInfo = value; }
}
[XmlIgnore]
public Boolean DimensionInfoSpecified
{
get { return CheckDimensionContaining(); }
}
public Entry()
{
Key = String.Empty;
CheckDimensionContaining();
}
private Boolean CheckDimensionContaining()
{
return _containsDimensionInfo = _dimensionInfo != default(DimensionInfo);
}
}
Here the magic begins. With using selective XmlIgnoreAttribute we can decide the ways the object serializes. The main class only wraps a list of Entries:
[Serializable]
[XmlRoot("metadata")]
public class Metadata
{
[XmlElement("entry")]
public List<Entry> Entries { get; set; }
public Metadata()
{
Entries = new List<Entry>();
}
}
How it is made: entry contains dimensionInfo if it exists, and false if it does not. Try out the code sample in console:
Metadata metadata = new Metadata();
metadata.Entries.Add(new Entry()); //Adding empty entry
//Adding entry with info
metadata.Entries.Add(new Entry() { DimensionInfo = new DimensionInfo() });
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Metadata));
using (FileStream fileStream = new FileStream("info.txt", FileMode.Create))
{
xmlSerializer.Serialize(fileStream, metadata);
}
It gave me the following output:
<metadata>
<entry key="">false</entry>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
</metadata>
However, this code is not perfect and there's a lot of things to improve, but now you have an idea of how it works
If you ever encounter XML files that you need to consume via .Net there is a tool XML Schema Definition Tool (Xsd.exe) that does the conversion automatically.
Its a command-line tool and to open it you use the Start > All
Programs > Visual Studio 2008/10/12/13 > Visual Studio Tools > Visual
Studio Command Prompt
The syntax to create a class from the XML file is described in the MSDN article. I'll give you an overview of the process to get you started.
Save the xml file to the temp dirtectory:
<metadata>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
<entry key="">false</entry>
</metadata>
Fire up the Visual Studio Command Prompt
To find out all the options enter xsd /?
Now you need to convert the XML file to a XSD file, this is the command:
xsd "C:\temp\File.xml" /c /outputdir:c:\temp
This will create an XSD file in the temp directory.
Then to convert the XSD file to a Serializable C# class this is the command:
xsd "C:\temp\File.xsd" /c /outputdir:c:\temp
This is the resulting C# Serialized class file:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class metadata {
private metadataEntry[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("entry", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public metadataEntry[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class metadataEntry {
private metadataEntryDimensionInfo[] dimensionInfoField;
private string keyField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("dimensionInfo", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public metadataEntryDimensionInfo[] dimensionInfo {
get {
return this.dimensionInfoField;
}
set {
this.dimensionInfoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string key {
get {
return this.keyField;
}
set {
this.keyField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class metadataEntryDimensionInfo {
private string enabledField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string enabled {
get {
return this.enabledField;
}
set {
this.enabledField = value;
}
}
}
Sounds like;
public class Metadata
{
private Dictionary<string, object> entry;
}
Where the dictionary has two item; "false" and another object;
public class dimensionInfo
{
public bool enabled = false;
}
However, you have 2 keys that are empty string. Are you sure the keys shouldn't have a value?
Actually you can create your own custom serialization for any class, so you don't have to stick to the schema when implementing your class.
All you have to do is to create a class which implements the IXmlSerializable interface
You can read more on the topic here:
Custom XML serialization
Otherwise you can use Attributes to control XML serialization.
Using [XmlAttribute] results in serialization as attribute.
Using [XmlText] results in serialization as inner text in the node. (Like the false string inside the other element in your example XML.)
Example:
public class Program
{
static void Main(string[] args)
{
Metadata meta = new Metadata();
meta.entry = new List<Entry>();
var dim = new dimensionInfo();
meta.entry.Add(
new Entry()
{
key = "",
O = dim
}
);
meta.entry.Add(
new Entry()
{
key = "",
text = "false",
O = null
}
);
XmlWriterSettings set = new XmlWriterSettings();
set.NamespaceHandling = NamespaceHandling.OmitDuplicates;
set.OmitXmlDeclaration = true;
set.DoNotEscapeUriAttributes = false;
set.Indent = true;
set.NewLineChars = "\n\r";
set.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(Console.Out, set);
XmlSerializer ser = new XmlSerializer(typeof(Metadata), "");
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
ser.Serialize(writer, meta, namespaces);
}
[XmlRoot("metadata")]
public class Metadata
{
[XmlElement]
public List<Entry> entry;
}
public class dimensionInfo
{
[XmlElement]
public bool enabled = false;
}
public class Entry
{
[XmlAttribute] // serialized as attribute
public string key = "";
[XmlText] // serialized as text node
public string text = "";
[XmlElement("dimensionInfo")] // serialized as an element
public dimensionInfo O = null;
}
}
This resulted the following XML:
<metadata>
<entry key=""><dimensionInfo><enabled>false</enabled></dimensionInfo></entry>
<entry key="">false</entry>
</metadata>
You can use XSD.exe to autoGenerate C# class in which you can serialize.
A straight forward answer:
Having your class to implement IXmlSerializable interface and using an XmlSerializer to defining the behavior for all the cases you desire.
private DimensionInfo _value;
public void WriteXml(XmlWriter writer)
{
var valueSerializer = new XmlSerializer(typeof (DimensionInfo));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
writer.WriteStartElement("entry");
writer.WriteAttributeString("key", string.Empty, string.Empty);
// Here you define how you want your XML structure to look like
// E.g. write an empty XML node in case of a null value
if (_value != null)
{
valueSerializer.Serialize(writer, value, ns);
}
writer.WriteEndElement();
}
Would produce this in XML
<entry key="">
<dimensionInfo>
<enabled>true</enabled>
</dimensionInfo>
</entry>
Or in case of a null value
<entry key="" />
A more detailed example with a XmlSerializableDictionary:
I used an XmlSerializableDictionary approach to produce the XML you provided. Again, you can specify precisely how the produced XML should look like in the WriteXml method.
[XmlRoot("metadata")]
public class XmlSerializableDictionary<TValue> : Dictionary<string, TValue>, IXmlSerializable where TValue : class
{
private const string XmlKeyName = "key";
private const string XmlValueName = "entry";
public void WriteXml(XmlWriter writer)
{
var valueSerializer = new XmlSerializer(typeof (TValue));
var ns = new XmlSerializerNamespaces(); ns.Add("", "");
foreach (var key in Keys)
{
writer.WriteStartElement(XmlValueName);
writer.WriteAttributeString(XmlKeyName, string.Empty, key);
var value = this[key];
// Only serialize the value if value is not null, otherwise write the
// empty XML element.
if (value != null)
{
valueSerializer.Serialize(writer, value, ns);
}
writer.WriteEndElement();
}
}
public void ReadXml(XmlReader reader) { /* left out */ }
public XmlSchema GetSchema() { return null; }
}
The DimensionInfo type for reference
[XmlRoot("dimensionInfo")]
public class DimensionInfo
{
[XmlElement("enabled")]
public Boolean Enabled { get; set; }
}
The following code serializes the dictionary to XML
var xmlSerializableDictionary = new XmlSerializableDictionary<DimensionInfo>
{
{"justakey", new DimensionInfo {Enabled = true}},
{"anotherkey", null}
};
var xmlSerializer = new XmlSerializer(typeof (SerializableDictionary<DimensionInfo>));
xmlSerializer.Serialize(File.Open(#"D:\xmlSerializedDictionary.xml", FileMode.Create), serializableDictionary);
Produced XML file:
<?xml version="1.0"?>
<metadata>
<entry key="justakey">
<dimensionInfo>
<enabled>true</enabled>
</dimensionInfo>
</entry>
<entry key="anotherkey" />
</metadata>
UPDATE: 11/26/2012
I've updated my autogenerated c# classes using wsdl.exe instead of svcutil, so I could get SOAP attributes in the proxy classes (i'm calling a SOAP service). My original problem was serializing, but with help from markus, I'm able to serialize now. But now I get an error back from the service:
Invalid request object: It must be a Query Request
The xml which works when I hard-code it:
<xml version="1.0"?><Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Header/><Body>
<QueryRequest xmlns="http://emkt.pjm.com/emkt/xml">
<QueryMarketResults type="Virtual" day="2012-11-16"><All/>
</QueryMarketResults></QueryRequest></Body></Envelope>
The xml it's generating is:
<?xml version="1.0" encoding="utf-16"?>
<QueryRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://emkt.pjm.com/emkt/xml">
<QueryMarketResults day="2012-11-16" type="Virtual">
<All />
</QueryMarketResults>
</QueryRequest>
I'm missing the envelope and body tags. I tried serializing as below, but got error "there was an error generating the XML document".
XmlTypeMapping myTypeMapping = (new SoapReflectionImporter().ImportTypeMapping(typeof (QueryRequest)));
XmlSerializer serializer = new XmlSerializer(myTypeMapping);
Here are the relevant proxy classes: (I added the [XmlRoot] attributes below on QueryRequest which did add the correct namespace)
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=false, Namespace="http://emkt.pjm.com/emkt/xml")]
[XmlRoot(Namespace = "http://emkt.pjm.com/emkt/xml")]
public partial class QueryRequest {
private object[] itemsField;
private ItemsChoiceType1[] itemsElementNameField;
[System.Xml.Serialization.XmlElementAttribute("QueryPortfolios", typeof(QueryPortfoliosType))]
[System.Xml.Serialization.XmlElementAttribute("QueryVirtualBid", typeof(QueryByAllLocationDayType))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType1[] ItemsElementName {
get {
return this.itemsElementNameField;
}
set {
this.itemsElementNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://emkt.pjm.com/emkt/xml", IncludeInSchema=false)]
public enum ItemsChoiceType1 {
QueryPortfolios,
QueryVirtualBid,
}
Thanks for all your help!
The constructors does not assign any value to the arrays, so they will be null.
Try this:
var qr = new QueryRequest
{
ItemsElementName = new ItemsChoiceType1[] {
ItemsChoiceType1.QueryMarketResults,
},
Items = new object[] {
new QueryByAllLocationDayTypeType
{
ItemElementName = ItemChoiceType3.All,
Item = new QueryAllType(),
day = Convert.ToDateTime("2012-11-16"),
type = MarketQueryTypeType.Virtual,
},
},
}
Or, equivalently without object initializers:
var qmr = new QueryByAllLocationDayTypeType();
qmr.ItemElementName = ItemChoiceType3.All;
qmr.Item = new QueryAllType();
qmr.day = Convert.ToDateTime("2012-11-16");
qmr.type = MarketQueryTypeType.Virtual;
var qr = new QueryRequest();
qr.ItemsElementName = new ItemsChoiceType1[1];
qr.ItemElementName[0] = ItemsChoiceType1.QueryMarketResults;
qr.Items = new object[1];
qr.Items[0] = qmr;