is there a simple way to remove the namespace from the XML root element. I have tried with
[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]
on the serializable class. But no use. still getting the same result.
sample class
[Serializable]
[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]
public class BINDRequest
{
public BINDRequest()
{
}
[XmlAttribute]
public string CLIENT_REQUEST_ID { get; set; }
public BINDRequestBody BIND { get; set; }
}
result xml
<?xml version="1.0" encoding="utf-8"?>
<MCP xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" CLIENT_REQUEST_ID="1">
<BIND CLIENT_ID="test" PASSWORD="test" />
</MCP>
i don't understand then whats the use of specifying namsespace in XmlRootAttribute??
Try this:
public class BINDRequest
{
[XmlAttribute]
public string CLIENT_REQUEST_ID { get; set; }
}
class Program
{
static void Main()
{
var request = new BINDRequest
{
CLIENT_REQUEST_ID = "123"
};
var serializer = new XmlSerializer(request.GetType());
var xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
using (var writer = XmlWriter.Create("result.xml"))
{
serializer.Serialize(writer, request, xmlnsEmpty);
}
}
}
Related
I need to serialize a class to xml. If a certain condition is met at run-time, I want to add an XML attribute to an element and assign it a value. Sometimes, the "Error" attribute will appear and sometimes it won't.
My code that serializes my objects:
public class XmlToolsRepo : IXmlTools
{
public string SerializeToXML<T>(object obj)
{
string results = null;
Encoding enc = Encoding.UTF8;
using (MemoryStream ms = new MemoryStream())
{
using (XmlTextWriter xw = new XmlTextWriter(ms, enc))
{
xw.Formatting = Formatting.None;
XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
XmlSerializer xSerializer = new XmlSerializer(typeof(T));
xSerializer.Serialize(xw, obj, emptyNS);
}
results = enc.GetString(ms.ToArray());
}
return results;
}
}
A class with a property that could have a new attribute at run-time:
[DataContract]
public class H204
{
[DataMember]
[XmlAttribute]
public string Code { get; set; }
[DataMember]
public string DW { get; set; }
}
When a condition is met I need for the XML to look like this:
<?xml version="1.0" encoding="UTF-8"?>
<H204 Code="A">
<DW Error="test" />
</H204>
Try following :
public class H204
{
[XmlAttribute(AttributeName = "Code")]
public string Code { get; set; }
[XmlElement(ElementName = "DW")]
public DW dw{ get; set; }
}
public class DW
{
[XmlAttribute(AttributeName = "Error")]
public string text { get; set; }
}
I've been looking here for a sollution, but I did not find it in previous answers.
I need to create the following xml with the serialiser
<?xml version="1.0" encoding="Windows-1252"?>
<documents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<document>
<Keys>
<drawer>GraphicData</drawer>
<somedata>otherData</somedata>
</Keys>
<otherGenericProperties>
<Data>GenericData 2</Data>
</otherGenericProperties>
<Repeat>
<FileInfo mimeType="application/pdf" HREF="PdfFile.pdf" />
</Repeat>
<Repeat>
<FileInfo mimeType="application/pdf" HREF="PdfFile2.pdf" />
</Repeat>
</document>
</documents>
The data consist of a few classes
namespace test
{
public class Documents
{
[XmlElement("Keys")] // this is used so the destination name can change in the future
public Keys keys { get; set; }
}
public class document
{
[XmlElement("Keys")] // this is used so the destination name can change in the future
public Keys keys { get; set; }
[XmlElement("Repeat")] // This does not work
List<Repeat> listRepeat { get; set; }
}
public class Keys
{
[XmlElement("drawer")]
public string drawer { get; set; }
}
public class Repeat
{
[XmlElement("fileInfo")]
public FileInfo fileInfo { get; set; }
}
public class FileInfo
{
public string FileInfo { get; set; }
[XmlAttribute("mimeType")]
public string mimeType { get; set; }
[XmlAttribute("mimeType")]
public string HREF { get; set; }
}
}
the serialiser :
XmlSerializer serializer = new XmlSerializer(typeof(Documents));
using (StreamWriter writer = new StreamWriter(saveBestand, false, xmlEncoding))
{
serializer.Serialize(writer, icm, namespaces);
}
I really need the xm like the example, and also the xml names should be changable by a contract like xmlElement is used for. Somehow the repeat element cant be placed on the level you see in the example. Does anyone have a sollution ?
you have two options.
Option 1
use xsd.exe to generate classes using the xml you want.
xsd yourxmlfile.xml
xsd yourxmlfile.xsd /classes
This will generate classes which you can use for serialization or deserialization.
Option 2:
Paste special option to generate the c# classes.
This does not involve using the command line.
refer blog at: https://dennymichael.net/2014/05/30/convert-xml-to-csharp-classes/comment-page-1/
It seems that you poorly designed your data classes. Try solution below.
public class OtherGenericProperties
{
[XmlElement("Data")]
public string Data { get; set; }
}
[XmlRoot("documents")]
public class Documents
{
[XmlElement("document")]
public Document Document { get; set; }
}
public class Document
{
[XmlElement("Keys")] // this is used so the destination name can change in the future
public Keys Keys { get; set; }
[XmlElement("otherGenericProperties")]
public OtherGenericProperties OtherGenericProperties { get; set; }
[XmlElement("Repeat")] // This does not work
public List<Repeat> ListRepeat { get; set; }
}
public class Keys
{
[XmlElement("drawer")]
public string Drawer { get; set; }
[XmlElement("somedata")]
public string SomeData { get; set; }
}
public class Repeat
{
[XmlElement("FileInfo")]
public FileInfo FileInfo { get; set; }
}
public class FileInfo
{
[XmlAttribute("mimeType")]
public string MimeType { get; set; }
[XmlAttribute("HREF")]
public string Href { get; set; }
}
Serializing:
internal static void Test()
{
var doc = new Documents
{
Document = new Document
{
Keys = new Keys
{
Drawer = "GraphicData",
SomeData = "otherData"
},
OtherGenericProperties = new OtherGenericProperties { Data = "GenericData 2" },
ListRepeat = new List<Repeat>
{
new Repeat { FileInfo =new FileInfo { Href = "PdfFile.pdf", MimeType = "application/pdf" } },
new Repeat { FileInfo = new FileInfo { Href = "PdfFile2.pdf", MimeType = "application/pdf" } }
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Documents));
using (var f = new StreamWriter("D:\\doc.xml", false, Encoding.GetEncoding("Windows-1252")))
{
serializer.Serialize(f, doc);
f.Flush();
}
}
Output:
<?xml version="1.0" encoding="Windows-1252"?>
<documents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<document>
<Keys>
<drawer>GraphicData</drawer>
<somedata>otherData</somedata>
</Keys>
<otherGenericProperties>
<Data>GenericData 2</Data>
</otherGenericProperties>
<Repeat>
<FileInfo mimeType="application/pdf" HREF="PdfFile.pdf" />
</Repeat>
<Repeat>
<FileInfo mimeType="application/pdf" HREF="PdfFile2.pdf" />
</Repeat>
</document>
</documents>
I'm trying to obtain the value of the logicalName attribute of the main node of this xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<ticketlayout xmlns="http://www.example.com/ticketlayout" logicalName="target.xml" deviceCode="1" measurement="mm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/ticketlayout">
<fontdefinition id="BarCode">
<fontname>Code128bWin</fontname>
<size measure="pt">16</size>
</fontdefinition>
</ticketlayout>
I've tried to add the namespace "xsi", "http://www.w3.org/2001/XMLSchema-instance" this way:
XmlDocument fLayout = new XmlDocument();
fLayout.Load("myFile.xml");
XmlNamespaceManager nsmRequestLayout = new XmlNamespaceManager(fLayout.NameTable);
nsmRequestLayout.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
string sValue = fLayout.SelectNodes("//ticketlayout", nsmRequestLayout)[0].Attributes["name"].Value;
But I get no nodes. I've tried without namespace and no nodes again, and son on.
¿Could please anyone help me?
Thanks in advance.
If you want to get the value : target.xml
Try this code
XmlDocument fLayout = new XmlDocument();
fLayout.Load("myFile.xml"); // your XML file
var attrib = fLayout["ticketlayout"].Attributes["logicalName"].Value;
First of all your XML is not valid.
I modified to look this way in order to achieve what you are looking for.
XML File :
<?xml version="1.0" encoding="UTF-8"?>
<ticketlayout xmlns="http://www.example.com/ticketlayout" logicalName="target.xml" deviceCode="1" measurement="mm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/ticketlayout">
<fontdefinition id="BarCode">
<fontname>Code128bWin</fontname>
<size measure="pt">16</size>
</fontdefinition>
</ticketlayout>
I am not sure why you would not have a model structure to deserialize you xml, and then access whatever property/attribute you need.
Example :
Classes:
[XmlRoot(ElementName = "size", Namespace = "http://www.example.com/ticketlayout")]
public class Size
{
[XmlAttribute(AttributeName = "measure")]
public string Measure { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "fontdefinition", Namespace = "http://www.example.com/ticketlayout")]
public class Fontdefinition
{
[XmlElement(ElementName = "fontname", Namespace = "http://www.example.com/ticketlayout")]
public string Fontname { get; set; }
[XmlElement(ElementName = "size", Namespace = "http://www.example.com/ticketlayout")]
public Size Size { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "ticketlayout", Namespace = "http://www.example.com/ticketlayout")]
public class Ticketlayout
{
[XmlElement(ElementName = "fontdefinition", Namespace = "http://www.example.com/ticketlayout")]
public Fontdefinition Fontdefinition { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName = "logicalName")]
public string LogicalName { get; set; }
[XmlAttribute(AttributeName = "deviceCode")]
public string DeviceCode { get; set; }
[XmlAttribute(AttributeName = "measurement")]
public string Measurement { get; set; }
[XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string SchemaLocation { get; set; }
}
Then you could use a serializer :
public class Serializer
{
public T Deserialize<T>(string input) where T : class
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StringReader stringReader = new StringReader(input))
{
return (T)xmlSerializer.Deserialize(stringReader);
}
}
public string Serialize<T>(T ObjectToSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());
StringBuilder builder = new StringBuilder();
using (StringWriterWithEncoding textWriter = new StringWriterWithEncoding(builder, Encoding.UTF8))
{
xmlSerializer.Serialize(textWriter, ObjectToSerialize);
return textWriter.ToString();
}
}
}
public class StringWriterWithEncoding : StringWriter
{
Encoding encoding;
public StringWriterWithEncoding(StringBuilder builder, Encoding encoding)
: base(builder)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}
And finally you can access whatever you want by doing the following :
var serializer = new Serializer();
//I used a local file for testing, but it should be the same thing with your file
var xmlInputData = File.ReadAllText(#"MyXmlPath");
var output = serializer.Deserialize<Ticketlayout >(xmlInputData);
var logicalName = output.LogicalName;
I am having some issue with deserialising some XML to an object list, always getting count 0 and within that "raw data" when inspecting DateAndTimeSlot during debug.
Unfortunately I cannot change the names of these elements.
However when checking the XML I get back, there are DateAndTimeslot objects in the XML.
With other object lists I have all seems fine, without the inclusion of namespaces.
What have I missed?
C# Code:
[XmlRoot("AppointmentAvailabilityStatusResponse")]
public class CheckAppointmentAvailabilityContainer
{
[XmlElement("AppointmentAvailabilityStatusResult")]
public AppointmentAvailabilityStatus appointmentAvailabilityStatus { get; set; }
}
[XmlRoot("AppointmentAvailabilityStatusResult", Namespace = "Appointments")]
public class AppointmentAvailabilityStatus
{
[XmlArray("DateAndTimeSlot", Namespace = "Appointments")]
[XmlArrayItem(typeof(DateAndTimeslot))]
public DateAndTimeSlots DateAndTimeSlot { get; set; }
[XmlElement("RequestedStatus")]
public int RequestedStatus { get; set; }
}
[XmlRoot(ElementName = "DateAndTimeSlot")]
[XmlType("a")]
public class DateAndTimeSlots : List<DateAndTimeslot> { }
[XmlRoot(ElementName = "DateAndTimeslot", Namespace = "Appointments.TO")]
[XmlType("b")] // if included this renames the node to "b" for some reason
public class DateAndTimeslot
{
[XmlElement("Date")]
public string Date { get; set; }
[XmlElement("TimeSlot")]
public string TimeSlot { get; set; }
}
Shortened XML returned that I wish to fully deserialise.
<AppointmentAvailabilityStatusResponse>
<AppointmentAvailabilityStatusResult xmlns:a="Appointments" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:DateAndTimeSlot xmlns:b="Appointments.TO">
<b:DateAndTimeslot>
<b:Date>14/07/2016</b:Date>
<b:TimeSlot>AM</b:TimeSlot>
</b:DateAndTimeslot>
<b:DateAndTimeslot>
<b:Date>14/07/2016</b:Date>
<b:TimeSlot>PM</b:TimeSlot>
</b:DateAndTimeslot>
</a:DateAndTimeSlot>
<a:RequestStatus>0</a:RequestStatus>
</AppointmentAvailabilityStatusResult>
</AppointmentAvailabilityStatusResponse>
XML if I serialise a dummy object - some differences which I'm trying to rectify, not sure if the namespaces are necessary for deserialisation though
<AppointmentAvailabilityStatusResponse>
<AppointmentAvailabilityStatusResult>
<DateAndTimeSlot xmlns=\"Appointments\">
<DateAndTimeslot>
<Date xmlns=\"Appointments.TO\">today</Date>
<TimeSlot xmlns=\"Appointments.TO\">now</TimeSlot>
</DateAndTimeslot>
</DateAndTimeSlot>
<RequestedStatus xmlns=\"Appointments\">0</RequestedStatus>
</AppointmentAvailabilityStatusResult>
</AppointmentAvailabilityStatusResponse>
Deserialiser
public static T DeserializeThis<T>(string cleanXml)
{
//string cleanXml = RemoveBom(dirtyXml);
bool check = cleanXml.TrimStart().StartsWith("<");
if (!string.IsNullOrEmpty(cleanXml) && cleanXml.TrimStart().StartsWith("<"))
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(T));
MatchCollection mc = Regex.Matches(cleanXml, #"</?(\d\w+)");
List<string> elements = new List<string>();
foreach (Match m in mc)
{
string cpval = m.Groups[1].Value;
if (!elements.Contains(cpval)) { elements.Add(cpval); }
}
foreach (string e in elements)
{
cleanXml = cleanXml.Replace(e, "d_" + e);
}
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(cleanXml)))
{
using (StringReader sr = new StringReader(cleanXml))
{
return (T)xs.Deserialize(sr);
}
}
}
catch(XmlException x)
{
var obj = (T)Activator.CreateInstance(typeof(T));
Type type = obj.GetType();
return (T)obj;
}
}
else
{
var obj = (T)Activator.CreateInstance(typeof(T));
Type type = obj.GetType();
// add in the generic derived class property search and assign
return (T)obj;
}
}
Thank you to those who commented above - I finally got it working. Removing the XmlArray and not including Anonymous and IsNullable attributes seemed to be the issue although I am unsure why as it works with all of the other functions I have, serializable possibly doesn't need to be present either.
Working class structure minus the container as that didn't change:
[Serializable()]
[XmlType(AnonymousType = true, Namespace = "")]
public class AppointmentAvailabilityStatusResult : WebserviceMessage
{
[XmlElement("DateAndTimeSlot", Namespace = "Appointments")]
public DateAndTimeSlot DateAndTimeSlot { get; set; }
[XmlElement("RequestedStatus")]
public int RequestedStatus { get; set; }
}
[Serializable()]
[XmlType(AnonymousType = true, Namespace = "Appointments")]
[XmlRoot(ElementName = "DateAndTimeSlot",Namespace = "Appointments", IsNullable = false)]
public class DateAndTimeSlot
{
[XmlElement(ElementName = "DateAndTimeslot", Namespace = "Appointments.TO")]
public List<DateAndTimeslot> DateAndTimeslot { get; set; }
}
[Serializable()]
[XmlType(AnonymousType = true, Namespace = "Appointments.TO")]
[XmlRoot(Namespace = "Appointments.TO", IsNullable = false)]
public class DateAndTimeslot
{
[XmlElement("Date")]
public string Date { get; set; }
[XmlElement("TimeSlot")]
public string TimeSlot { get; set; }
}
I created classes from a DTD (over XSD and xsd.exe) for my C# project, so I could easily deserialize them into a model class in my code.
This is roughly how I do it:
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create(tipsfile.FullName, readerSettings);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Tips";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Tips), xRoot);
Tips tips = (Tips)serializer.Deserialize(reader);
reader.Close();
But, upon inspection of tips, I see that it holds no values at all from the original XML file. Also, I tried setting a breakpoint on the set-Body of a property of Tips, and it is never reached, although I know for sure that it has a value in the original XML file.
Why is the file not correctly deserialized into the class? Is something missing in my code?
Edit: Here is the Tips.cs file, which was auto-generated from the XSD
using System.Xml.Serialization;
namespace MyNs.Model
{
[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://tempuri.org/caravan_1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/caravan_1", IsNullable = false)]
public partial class Tips
{
private Chapter[] chapterField;
[System.Xml.Serialization.XmlElementAttribute("Chapter")]
public Chapter[] Chapter
{
get
{
return this.chapterField;
}
set
{
this.chapterField = value;
}
}
}
[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://tempuri.org/caravan_1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/caravan_1", IsNullable = false)]
public partial class Chapter
{
private string headingField;
private CarType[] carTypesField;
private Section[] sectionField;
private string countryField;
private string languageField;
public string Heading
{
get
{
return this.headingField;
}
set
{
this.headingField = value;
}
}
[System.Xml.Serialization.XmlArrayItemAttribute("CarType", IsNullable = false)]
public CarType[] CarTypes
{
get
{
return this.carTypesField;
}
set
{
this.carTypesField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("Section")]
public Section[] Section
{
get
{
return this.sectionField;
}
set
{
this.sectionField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Country
{
get
{
return this.countryField;
}
set
{
this.countryField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Language
{
get
{
return this.languageField;
}
set
{
this.languageField = value;
}
}
}
[... and so on ...]
And a sample XML file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Tips SYSTEM "caravan_1.dtd">
<Tips>
<Chapter Country="dafghagt" Language="de">
<Heading>fgagasgargaergarg</Heading>
<Section id="1">
<Heading>afdhwr6u5taehtaqh5</Heading>
<SubSection id="1">
<Heading>46k46kw6jhadfgadfha</Heading>
<Table>
<Row id="1">
<Heading>sgjsfgjsgfh443q572q356</Heading>
<Items>
<Item car="motor1" id="1">
<BodyText color="red">130*</BodyText>
<Subscript>3</Subscript>
</Item>
</Items>
</Row>
</Table>
</SubSection>
</Section>
</Chapter>
</Tips>
StreamReader sw = new StreamReader(fileName, false);
XmlTextReader xmlw = new XmlTextReader(sw);
XmlSerializer writer = new XmlSerializer(
type,
GetOverrides(),
extraTypes,
null,
null);
object o = writer.Deserialize(xmlw);
As per my comment, get overrides is just a method that contains something similar to your xml root attribute, I can show you this too if necessary
EDIT:
an example of extra types
public Type[] GetTypes()
{
return new Type[] { typeof(Class1), typeof(Class2)};
}
EDIT2: get overrides returns (Note this is untested)
XmlAttributes attribs = new XmlAttributes();
//attribs.XmlRoot - can edit root here (instead of xmlrootattribute)
attribs.XmlElements.Add(myAttribute);
XmlAttributeOverrides myOverride = new XmlAttributeOverrides();
myOverride.Add(typeof(Tips), "Tips", attribs);
return myOverride
Your object may not be identical to the xml model. In that case, you need map the properties of your class to the xml fields. I am giving you a quick example I had in one of my projects which may give you bit more information.
namespace DatabaseModel
{
[Description("Represents the selected nodes in the Coverage pane")]
[Serializable()]
[XmlRootAttribute("XmlCoverage", Namespace = "GISManager", IsNullable = false)]
public class TXmlCoverage : IXmlPolygon
{
[XmlArray(ElementName = "sbets"), XmlArrayItem(ElementName = "sbet")]
public List SbetsSelected { get; set; }
[XmlArray(ElementName = "sdcs"), XmlArrayItem(ElementName = "sdc")]
public List SdcsSelected { get; set; }
[XmlElementAttribute(ElementName = "area")]
public Boolean IsAreaSelected { get; set; }
[XmlElementAttribute(ElementName = "fpath")]
public Boolean IsFlightPathSelected { get; set; }
[XmlElementAttribute(ElementName = "fpoly")]
public Boolean IsFlightPolySelected { get; set; }
[XmlElementAttribute(ElementName = "mpoly")]
public Boolean IsMinePolySelected { get; set; }
[XmlElementAttribute(ElementName = "bldg")]
public Boolean IsBuildingsSelected { get; set; }
[XmlElementAttribute(ElementName = "hgt")]
public Boolean IsHeightSelected { get; set; }
[XmlIgnore()]
public Boolean ArePolygonsSelected { get { return IsMinePolySelected && IsBuildingsSelected && IsHeightSelected; } }
public TXmlCoverage()
{
SbetsSelected = new List<String>();
SdcsSelected = new List<String>();
IsAreaSelected = false;
IsFlightPathSelected = false;
IsFlightPolySelected = false;
}
}
}
So it turns out the problem is namespaces. Because my XML has no root namespace:
<Tips>
but the definition of my Model contained one:
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/caravan_1", IsNullable = false)]
the Serializer didn't match any elements together. When removing the namespace attribute, it worked fine.
So now, I reworked the complete model and excluded any attributes that were not absolutely necessary (as it turns out, all but one were), so now every Property has just one Attribute: XmlElement and consorts.
using System.Xml.Serialization;
namespace MyNs.Model
{
[XmlRoot("Tips")]
public partial class Tips
{
[XmlElement("Chapter")]
public Chapter[] Chapter { get; set; }
}
[XmlRoot("Chapter")]
public partial class Chapter
{
[XmlElement("Heading")]
public string Heading { get; set; }
[XmlElement("CarType")]
public CarType[] CarTypes { get; set; }
[XmlElement("Section")]
public Section[] Section { get; set; }
[XmlAttribute("Country")]
public string Country { get; set; }
[XmlAttribute("Language")]
public string Language { get; set; }
}
[... and so on ...]
With a simple deserialization it works just fine now:
XmlReaderSettings readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse };
XmlSerializer serializer = new XmlSerializer(typeof(Tips));
using (XmlReader reader = XmlReader.Create(fromXmlFile.FullName, readerSettings))
{
Tips tips = (Tips)serializer.Deserialize(reader);
return tips;
}