I am having a problem with serializing an object in C#. When the application goes to serialize the object, certain fields get serialized but others do not. In the following code:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ACORDInsuranceSvcRqHomePolicyQuoteInqRq
{
private string rqUIDField;
private System.DateTime transactionRequestDtField;
private System.DateTime transactionEffectiveDtField;
private string curCdField;
/// <remarks/>
public string RqUID
{
get
{
return this.rqUIDField;
}
set
{
this.rqUIDField = value;
}
}
/// <remarks/>
public string CurCd
{
get
{
return this.curCdField;
}
set
{
this.curCdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnore()]
public System.DateTime TransactionRequestDt
{
get
{
return this.transactionRequestDtField;
}
set
{
this.transactionRequestDtField = value;
}
}
/// <remarks/>
[XmlElement("TransactionRequestDt")]
public string TransactionRequestDtString
{
get
{
return String.Format("{0:yyyy-MM-dd}", this.TransactionRequestDt);
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnore]
public System.DateTime TransactionEffectiveDt
{
get
{
return this.transactionEffectiveDtField;
}
set
{
this.transactionEffectiveDtField = value;
}
}
/// <remarks/>
[XmlElement("TransactionEffectiveDt")]
public string TransactionEffectiveDtString
{
get
{
return String.Format("{0:yyyy-MM-dd}", this.TransactionEffectiveDt);
}
}
}
you can see that the Fields/Accessors RqUID and CurCd get called but TransactionRequestDtString and TransactionEffectiveDtString do not. I need all of these to be serialized. Thanks!
If they need to be xml serialized they need a public get and set.
Try changing your code to this:
[ReadOnly(true)]
[XmlElement("TransactionRequestDt")]
public string TransactionRequestDtString
{
get
{
return String.Format("{0:yyyy-MM-dd}", this.TransactionRequestDt);
}
set{}
}`
The ReadOnly attribute will not let anyone change it.
Possible answer see: Serializing private member data
I was facing the same issue with some properties(which are nullable) , i FIXED it by using : [XmlElement(IsNullable = true)] decorator
public class Person
{
[XmlElement(IsNullable = true)]
public string Name { get; set; }
}
Related
I have a wsdl document 3rd party and try to serialize request to XML.
I figured out that some values(like PaymentType), which were set to instance of the object are not serializing. Others do (like PersonName).
What could be the reason of such problem and how to fix it?
The problem is not in XML itself, while it's proxy generated. Looks there should be different reason on previous step or some setting.
Here is an example:
And XML classes of the 3rd party service.
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.3056.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://fedex.com/ws/rate/v24")]
public partial class CustomsClearanceDetail {
private BrokerDetail[] brokersField;
private ClearanceBrokerageType clearanceBrokerageField;
private bool clearanceBrokerageFieldSpecified;
private CustomsOptionDetail customsOptionsField;
private Party importerOfRecordField;
private RecipientCustomsId recipientCustomsIdField;
private Payment dutiesPaymentField;
private InternationalDocumentContentType documentContentField;
private bool documentContentFieldSpecified;
private Money customsValueField;
private FreightOnValueType freightOnValueField;
private bool freightOnValueFieldSpecified;
private Money insuranceChargesField;
private bool partiesToTransactionAreRelatedField;
private bool partiesToTransactionAreRelatedFieldSpecified;
private CommercialInvoice commercialInvoiceField;
private Commodity[] commoditiesField;
private ExportDetail exportDetailField;
private RegulatoryControlType[] regulatoryControlsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Brokers")]
public BrokerDetail[] Brokers {
get {
return this.brokersField;
}
set {
this.brokersField = value;
}
}
/// <remarks/>
public ClearanceBrokerageType ClearanceBrokerage {
get {
return this.clearanceBrokerageField;
}
set {
this.clearanceBrokerageField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ClearanceBrokerageSpecified {
get {
return this.clearanceBrokerageFieldSpecified;
}
set {
this.clearanceBrokerageFieldSpecified = value;
}
}
/// <remarks/>
public CustomsOptionDetail CustomsOptions {
get {
return this.customsOptionsField;
}
set {
this.customsOptionsField = value;
}
}
/// <remarks/>
public Party ImporterOfRecord {
get {
return this.importerOfRecordField;
}
set {
this.importerOfRecordField = value;
}
}
/// <remarks/>
public RecipientCustomsId RecipientCustomsId {
get {
return this.recipientCustomsIdField;
}
set {
this.recipientCustomsIdField = value;
}
}
/// <remarks/>
public Payment DutiesPayment {
get {
return this.dutiesPaymentField;
}
set {
this.dutiesPaymentField = value;
}
}
/// <remarks/>
public InternationalDocumentContentType DocumentContent {
get {
return this.documentContentField;
}
set {
this.documentContentField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool DocumentContentSpecified {
get {
return this.documentContentFieldSpecified;
}
set {
this.documentContentFieldSpecified = value;
}
}
/// <remarks/>
public Money CustomsValue {
get {
return this.customsValueField;
}
set {
this.customsValueField = value;
}
}
/// <remarks/>
public FreightOnValueType FreightOnValue {
get {
return this.freightOnValueField;
}
set {
this.freightOnValueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool FreightOnValueSpecified {
get {
return this.freightOnValueFieldSpecified;
}
set {
this.freightOnValueFieldSpecified = value;
}
}
/// <remarks/>
public Money InsuranceCharges {
get {
return this.insuranceChargesField;
}
set {
this.insuranceChargesField = value;
}
}
/// <remarks/>
public bool PartiesToTransactionAreRelated {
get {
return this.partiesToTransactionAreRelatedField;
}
set {
this.partiesToTransactionAreRelatedField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool PartiesToTransactionAreRelatedSpecified {
get {
return this.partiesToTransactionAreRelatedFieldSpecified;
}
set {
this.partiesToTransactionAreRelatedFieldSpecified = value;
}
}
/// <remarks/>
public CommercialInvoice CommercialInvoice {
get {
return this.commercialInvoiceField;
}
set {
this.commercialInvoiceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Commodities")]
public Commodity[] Commodities {
get {
return this.commoditiesField;
}
set {
this.commoditiesField = value;
}
}
/// <remarks/>
public ExportDetail ExportDetail {
get {
return this.exportDetailField;
}
set {
this.exportDetailField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("RegulatoryControls")]
public RegulatoryControlType[] RegulatoryControls {
get {
return this.regulatoryControlsField;
}
set {
this.regulatoryControlsField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.3056.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://fedex.com/ws/rate/v24")]
public partial class Payment {
private PaymentType paymentTypeField;
private bool paymentTypeFieldSpecified;
private Payor payorField;
/// <remarks/>
public PaymentType PaymentType {
get {
return this.paymentTypeField;
}
set {
this.paymentTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool PaymentTypeSpecified {
get {
return this.paymentTypeFieldSpecified;
}
set {
this.paymentTypeFieldSpecified = value;
}
}
/// <remarks/>
public Payor Payor {
get {
return this.payorField;
}
set {
this.payorField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.3056.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://fedex.com/ws/rate/v24")]
public enum PaymentType {
/// <remarks/>
SENDER,
}
For these types, and some others, there was an extra property in place within the generated classes. For instance, if one of the properties that wasn't working was named "Property1", then there was another property named "Property1Specified". The serialization would ignore those properties unless the "...Specified" one was set to true. Setting all of those properties specified properties to true now allows the serialization to display all expected elements.
As I said it was not about XML properties, or structure or smht like that. The reason was in setup of the XML and object to be serialized
I am getting this error when I run my code
System.InvalidOperationException
HResult=0x80131509
Message=HamiltonXML.Program is inaccessible due to its protection
level. Only public types can be processed.
Source=System.Xmlenter code here
StackTrace:
at System.Xml.Serialization.TypeDesc.CheckSupported()
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type,
MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at HamiltonXML.Program.Main(String[] args) in C:\Users\Aube\source\repos\HamiltonProject\HamiltonProject\Program.cs:line 18
I've changed all classes to public and rechecked all of the code yet the problem still occurs. Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace HamiltonXML
{
class Program
{
static void Main(string[] args)
{
EnvironmentNodeConfigurationParameters encp = null;
string path = "C:/Users/Aube/Desktop/FreezerEnvironmentNodeParameters_Freezer1.xml";
XmlSerializer serializer = new XmlSerializer(typeof(EnvironmentNodeConfigurationParameters));
StreamReader reader = new StreamReader(path);
encp = (EnvironmentNodeConfigurationParameters)serializer.Deserialize(reader);
reader.Close();
}
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class EnvironmentNodeConfigurationParameters
{
private EnvironmentNodeConfigurationParametersComplexNodeConfigurations[] complexDeviceParameterListField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("ComplexNodeConfigurations", IsNullable = false)]
public EnvironmentNodeConfigurationParametersComplexNodeConfigurations[] ComplexDeviceParameterList
{
get
{
return this.complexDeviceParameterListField;
}
set
{
this.complexDeviceParameterListField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class EnvironmentNodeConfigurationParametersComplexNodeConfigurations
{
private EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurations[] complexNodeParameterListField;
private string subDeviceIDField;
private string subDeviceNameField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("NodeConfigurations", IsNullable = false)]
public EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurations[] ComplexNodeParameterList
{
get
{
return this.complexNodeParameterListField;
}
set
{
this.complexNodeParameterListField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string SubDeviceID
{
get
{
return this.subDeviceIDField;
}
set
{
this.subDeviceIDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string SubDeviceName
{
get
{
return this.subDeviceNameField;
}
set
{
this.subDeviceNameField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurations
{
private EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParams environmentLinkParamsField;
private byte nodeIDField;
private string nodeNameField;
private string dependNodeNameField;
private string registerTypeField;
private byte startRegField;
private byte numRegsField;
private string nodeTypeField;
private string valueTypeField;
private string environmentLinkTypeField;
private string guidField;
private bool enabledField;
private string unitsField;
private bool monitoredField;
private byte reportItemField;
/// <remarks/>
public EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParams EnvironmentLinkParams
{
get
{
return this.environmentLinkParamsField;
}
set
{
this.environmentLinkParamsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte NodeID
{
get
{
return this.nodeIDField;
}
set
{
this.nodeIDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string NodeName
{
get
{
return this.nodeNameField;
}
set
{
this.nodeNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DependNodeName
{
get
{
return this.dependNodeNameField;
}
set
{
this.dependNodeNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string RegisterType
{
get
{
return this.registerTypeField;
}
set
{
this.registerTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte StartReg
{
get
{
return this.startRegField;
}
set
{
this.startRegField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte NumRegs
{
get
{
return this.numRegsField;
}
set
{
this.numRegsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string NodeType
{
get
{
return this.nodeTypeField;
}
set
{
this.nodeTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ValueType
{
get
{
return this.valueTypeField;
}
set
{
this.valueTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string EnvironmentLinkType
{
get
{
return this.environmentLinkTypeField;
}
set
{
this.environmentLinkTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Guid
{
get
{
return this.guidField;
}
set
{
this.guidField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool Enabled
{
get
{
return this.enabledField;
}
set
{
this.enabledField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Units
{
get
{
return this.unitsField;
}
set
{
this.unitsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool Monitored
{
get
{
return this.monitoredField;
}
set
{
this.monitoredField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte ReportItem
{
get
{
return this.reportItemField;
}
set
{
this.reportItemField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParams
{
private EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParamsKeyValuePair keyValuePairField;
/// <remarks/>
public EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParamsKeyValuePair KeyValuePair
{
get
{
return this.keyValuePairField;
}
set
{
this.keyValuePairField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class EnvironmentNodeConfigurationParametersComplexNodeConfigurationsNodeConfigurationsEnvironmentLinkParamsKeyValuePair
{
private string keyField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
}
}
The code is supposed to deserialize an XML file.
Have you tried changing your Program class to public?
namespace HamiltonXML
{
public class Program
{
This is my XML file.
<getMetadata>
<Project Name="Doors_Demo">
<Module FullPath="/Doors_Demo/Test_Module2">
<Attributes>
<Attribute name="TableType" type="TableType" />
<Attribute name="TableTopBorder" type="TableEdgeType" />
</Attributes>
</Module>
</Project>
</getMetadata>
I want to deserialize the above XML
Below is my code:
[XmlRoot("getMetadata")]
public class RootClass
{
public Project element_Project;
[XmlElement("Project")]
public Project Project
{
get { return element_Project; }
set { element_Project = value; }
}
}
public class Project
{
public string name;
[XmlAttribute("Name")]
public string Id
{
get { return name; }
set { name = value; }
}
}
public static void Main(string[] args)
{
RootClass obj = new RootClass();
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (FileStream stream = new FileStream(#"E:\getMetadata(4).xml", FileMode.Open))
{
RootClass myxml = (RootClass)serializer.Deserialize(stream);
Console.WriteLine(myxml.Project.name);
}
}
I want to deserialize my XML into a list, I am not able to access all inner elements and attributes inside the root element.
I want details of module element and its inner elements and tags into list which can be accessed.
Here is a little trick to generate classes from your XML automatically.
First, create a new empty class, name it for example TempXml.
Copy your XML to the clipboard and open the new empty class you just created.
Go to Visual Studio Edit menu then Paste Special and Paste XML as Classes:
This will generate the following code:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getMetadata
{
private getMetadataProject projectField;
/// <remarks/>
public getMetadataProject Project
{
get
{
return this.projectField;
}
set
{
this.projectField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProject
{
private getMetadataProjectModule moduleField;
private string nameField;
/// <remarks/>
public getMetadataProjectModule Module
{
get
{
return this.moduleField;
}
set
{
this.moduleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModule
{
private getMetadataProjectModuleAttribute[] attributesField;
private string fullPathField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Attribute", IsNullable = false)]
public getMetadataProjectModuleAttribute[] Attributes
{
get
{
return this.attributesField;
}
set
{
this.attributesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string FullPath
{
get
{
return this.fullPathField;
}
set
{
this.fullPathField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModuleAttribute
{
private string nameField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
Which should work fine with the XmlSerializer class.
You can clean up a little bit the generated output by removing the empty remarks, changing the name of the classes to use camel case (in this case you need to specify the real element name in the attribute as you were doing in your question) or move the classes to different files.
Hope it helps.
Could somebody help me generate C# class from XSD(sitemap with images)?
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>http://example.com/sample.html</loc>
<image:image>
<image:loc>http://example.com/image.jpg</image:loc>
</image:image>
<image:image>
<image:loc>http://example.com/photo.jpg</image:loc>
</image:image>
</url>
</urlset>
Here is my classes that were generated by xsd.exe tool:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true,
Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
IsNullable = false)]
public partial class urlset
{
private System.Xml.XmlElement[] anyField;
private List<tUrl> urlField;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get { return this.anyField; }
set { this.anyField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("url")]
public List<tUrl> url
{
get { return this.urlField; }
set { this.urlField = value; }
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
public partial class tUrl
{
private string locField;
private string lastmodField;
private tChangeFreq changefreqField;
private bool changefreqFieldSpecified;
private decimal priorityField;
private bool priorityFieldSpecified;
private System.Xml.XmlElement[] anyField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI")]
public string loc
{
get { return this.locField; }
set { this.locField = value; }
}
/// <remarks/>
public string lastmod
{
get { return this.lastmodField; }
set { this.lastmodField = value; }
}
/// <remarks/>
public tChangeFreq changefreq
{
get { return this.changefreqField; }
set { this.changefreqField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool changefreqSpecified
{
get { return this.changefreqFieldSpecified; }
set { this.changefreqFieldSpecified = value; }
}
/// <remarks/>
public decimal priority
{
get { return this.priorityField; }
set { this.priorityField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool prioritySpecified
{
get { return this.priorityFieldSpecified; }
set { this.priorityFieldSpecified = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get { return this.anyField; }
set { this.anyField = value; }
}
[System.Xml.Serialization.XmlElementAttribute(ElementName = "image", Type = typeof(image))]
public List<image> Images { get; set; }
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
public enum tChangeFreq
{
/// <remarks/>
always,
/// <remarks/>
hourly,
/// <remarks/>
daily,
/// <remarks/>
weekly,
/// <remarks/>
monthly,
/// <remarks/>
yearly,
/// <remarks/>
never,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true,
Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.google.com/schemas/sitemap-image/1.1",
IsNullable = false)]
public partial class image
{
private string locField;
private string captionField;
private string geo_locationField;
private string titleField;
private string licenseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "loc", DataType = "anyURI")]
public string loc
{
get { return this.locField; }
set { this.locField = value; }
}
/// <remarks/>
public string caption
{
get { return this.captionField; }
set { this.captionField = value; }
}
/// <remarks/>
public string geo_location
{
get { return this.geo_locationField; }
set { this.geo_locationField = value; }
}
/// <remarks/>
public string title
{
get { return this.titleField; }
set { this.titleField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI")]
public string license
{
get { return this.licenseField; }
set { this.licenseField = value; }
}
}
But I have problem with prefix 'image:', I could not sort out how to add this prefix to serialized xml. If I modify Element name by adding semicolon, then it do escape 'image_x003A_image'
I also used the xsd.exe tool and had the same issue. I resolved it as follows:
In the urlset class, add the following [XmlNamespaceDeclarations] property and create a constructor that adds the "image" xml namespace:
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
public urlset()
{
xmlns.Add("image", "http://www.google.com/schemas/sitemap-image/1.1");
}
In my case I only needed a single image, so I added the following attribute to my image property in tUrl
[XmlElement(Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
public image image
{
get
{
return this.imageField;
}
set
{
this.imageField = value;
}
}
This then added the "image:" prefix to all my image elements. You should be able to do something similar for you image list to associate it with the namespace you created above.
This post seems a little old, but hope this helps someone experiencing similar headaches trying to utilize the image sitemap schema extension.
I´m trying to deserialize the following XML:
#"<Activity type=""WOActivity"">
<ActionID>1</ActionID>
<ActionLog></ActionLog>
<ActionLogSummary>Add subcomponent</ActionLogSummary>
<UserID></UserID>
<FlexFields>
<FlexField mappedTo=""STATUS"" id=""0"">WAPPR</FlexField>
<FlexField mappedTo=""WOSEQUENCE"" id=""0"">10</FlexField>
<FlexField mappedTo=""OWNERGROUP"" id=""0"">V-PSB-DE-HLC-HWSUPPORT</FlexField>
</FlexFields>
I´ve also the following class, which was generated by the xsd:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2", IsNullable = false)]
public partial class Activity {
private string actionIDField;
private string actionLogField;
private string actionLogSummaryField;
private System.DateTime logDateTimeField;
private bool logDateTimeFieldSpecified;
private System.DateTime scheduledStartDateTimeField;
private bool scheduledStartDateTimeFieldSpecified;
private System.DateTime scheduledEndDateTimeField;
private bool scheduledEndDateTimeFieldSpecified;
private System.DateTime workBeginDateTimeField;
private bool workBeginDateTimeFieldSpecified;
private System.DateTime workEndDateTimeField;
private bool workEndDateTimeFieldSpecified;
private string userIDField;
private string userNameField;
private FlexFieldsFlexField[] flexFieldsField;
private string activityTypeField;
private string typeField;
private string indexField;
/// <remarks/>
public string ActionID {
get {
return this.actionIDField;
}
set {
this.actionIDField = value;
}
}
/// <remarks/>
public string ActionLog {
get {
return this.actionLogField;
}
set {
this.actionLogField = value;
}
}
/// <remarks/>
///
[System.Xml.Serialization.XmlElement]
public string ActionLogSummary {
get {
return this.actionLogSummaryField;
}
set {
this.actionLogSummaryField = value;
}
}
/// <remarks/>
public System.DateTime LogDateTime {
get {
return this.logDateTimeField;
}
set {
this.logDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool LogDateTimeSpecified {
get {
return this.logDateTimeFieldSpecified;
}
set {
this.logDateTimeFieldSpecified = value;
}
}
/// <remarks/>
public System.DateTime ScheduledStartDateTime {
get {
return this.scheduledStartDateTimeField;
}
set {
this.scheduledStartDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ScheduledStartDateTimeSpecified {
get {
return this.scheduledStartDateTimeFieldSpecified;
}
set {
this.scheduledStartDateTimeFieldSpecified = value;
}
}
/// <remarks/>
public System.DateTime ScheduledEndDateTime {
get {
return this.scheduledEndDateTimeField;
}
set {
this.scheduledEndDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ScheduledEndDateTimeSpecified {
get {
return this.scheduledEndDateTimeFieldSpecified;
}
set {
this.scheduledEndDateTimeFieldSpecified = value;
}
}
/// <remarks/>
public System.DateTime WorkBeginDateTime {
get {
return this.workBeginDateTimeField;
}
set {
this.workBeginDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool WorkBeginDateTimeSpecified {
get {
return this.workBeginDateTimeFieldSpecified;
}
set {
this.workBeginDateTimeFieldSpecified = value;
}
}
/// <remarks/>
public System.DateTime WorkEndDateTime {
get {
return this.workEndDateTimeField;
}
set {
this.workEndDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool WorkEndDateTimeSpecified {
get {
return this.workEndDateTimeFieldSpecified;
}
set {
this.workEndDateTimeFieldSpecified = value;
}
}
/// <remarks/>
public string UserID {
get {
return this.userIDField;
}
set {
this.userIDField = value;
}
}
/// <remarks/>
public string UserName {
get {
return this.userNameField;
}
set {
this.userNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("FlexField", IsNullable = false)]
public FlexFieldsFlexField[] FlexFields {
get {
return this.flexFieldsField;
}
set {
this.flexFieldsField = value;
}
}
/// <remarks/>
public string ActivityType {
get {
return this.activityTypeField;
}
set {
this.activityTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string index {
get {
return this.indexField;
}
set {
this.indexField = value;
}
}
}
I´ve made a unit test, but it fails because all the elements are null (second assert and forth). The type attribute is deserialized just fine.
What could be possibly be wrong?
PS: I´ve tried to add the namespace "http://b2b.ibm.com/schema/B2B_CDM_Incident/R2_2" to the serializer with no success...
PS2: the serialization seems to be working just fine for this class
Thanks.
string result = #"<Activity type=""WOActivity"">
<ActionID>1</ActionID>
<ActionLog></ActionLog>
<ActionLogSummary>Add subcomponent</ActionLogSummary>
<UserID></UserID>
<FlexFields>
<FlexField mappedTo=""STATUS"" id=""0"">WAPPR</FlexField>
<FlexField mappedTo=""WOSEQUENCE"" id=""0"">10</FlexField>
<FlexField mappedTo=""OWNERGROUP"" id=""0"">V-PSB-DE-HLC-HWSUPPORT</FlexField>
</FlexFields>
</Activity>";
var serializer = new XmlSerializer(typeof (Activity), new XmlRootAttribute("Activity"));
var first = (Activity)serializer.Deserialize(new XmlTextReader(new StringReader(result)));
Assert.AreEqual("WOActivity", first.type);
Assert.AreEqual("Add subcomponent", first.ActionLogSummary);
Assert.IsNotNull(first.FlexFields);
Assert.AreEqual(4, first.FlexFields.Count());
Just put the root element into the correct namespace:
string xml = #"<Activity type=""WOActivity""
xmlns=""http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2"">
...
</Activity>";
Note that because the namespace is inherited, everything else also uses that element.
This then works:
var ser = new XmlSerializer(typeof(Activity));
var activity = (Activity)ser.Deserialize(new StringReader(xml));
System.Console.WriteLine(activity.ActionID);
System.Console.WriteLine(activity.ActionLogSummary);
System.Console.WriteLine(activity.type);
with output:
1
Add subcomponent
WOActivity
In other scenarios, you may need to refer to multiple namespaces, or mention the same namespace multiple times. Then it becomes useful to declare an alias; the following is semantically identical to the first example in this answer:
string xml = #"<b2b:Activity type=""WOActivity""
xmlns:b2b=""http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2"">
<b2b:ActionID>1</b2b:ActionID>
<b2b:ActionLog></b2b:ActionLog>
<b2b:ActionLogSummary>Add subcomponent</b2b:ActionLogSummary>
...
</b2b:Activity>";
With the only difference that we can now use b2b: as a prefix on any element as an alternative to saying xmlns=""http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2"". Note also that alias-based namespaces are not inherited, unlike xmlns= namespaces.
just delete the two generated lines:
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2", IsNullable = false)]