XML Deserialize camt.053.001.04 field problem - c#

I do not know how to handle multiple XML Tags with the same name without doing arrays or List.
Original XML wihtout content:
`<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.04">
<BkToCstmrStmt>
<GrpHdr>
<MsgId></MsgId>
<CreDtTm></CreDtTm>
<MsgPgntn>
<PgNb></PgNb>
<LastPgInd></LastPgInd>
</MsgPgntn>
</GrpHdr>
<Stmt>
<Id></Id>
<ElctrncSeqNb></ElctrncSeqNb>
<CreDtTm></CreDtTm>
<FrToDt>
<FrDtTm></FrDtTm>
<ToDtTm></ToDtTm>
</FrToDt>
<Acct>
<Id>
<IBAN></IBAN>
</Id>
<Ccy></Ccy>
<Ownr>
<Nm></Nm>
<PstlAdr>
<AdrLine></AdrLine>
<AdrLine></AdrLine>
</PstlAdr>
</Ownr>
<Svcr>
<FinInstnId>
<BICFI></BICFI>
<Nm></Nm>
</FinInstnId>
</Svcr>
</Acct>
<Bal></Bal>
<Bal></Bal>
<Ntry></Ntry>
<Ntry></Ntry>
<Ntry></Ntry>
</BkToCstmrStmt></Document>`
Now im at AdrLine. Normaly i would think its something like string[] AdrLine.
But that is not the case here. string[] would generate following:
<AdrLine><string></string><string></string></AdrLine>
I know AdrLine must be a class or struct to achiev that structure. So i tested around with that but stuck at multiple lines and value without using array or list. What i currnently have is: <PstlAdr><AdrLine /></PstlAdr> If someone can enlighten me, that would be great pleasure. The Achievment should look like this: <PstlAdr><AdrLine>Line1</AdrLine><AdrLine>Line2</AdrLine></PstlAdr>
At the <Bal></Bal><Bal></Bal> or <Ntry></Ntry><Ntry></Ntry> i have the same Issue. Normaly i would think this is in a Array, but here this isn't the case too cause of the missing Array Tags around the <Bal></Bal> or <Ntry></Ntry> tags.
Serialize method with Generictype:
public static readonly string defaultFilePath = Application.StartupPath;
public static readonly string fileFormat = "xml";
public static void SaveAs<T>(T obj, string filename, string xmlNamespace = "")
{
string filePath = defaultFilePath + "/" + filename + "." + fileFormat;
using (FileStream outFile = File.Create(filePath))
{
if (File.Exists(filePath))
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType(), xmlNamespace);
xmlSerializer.Serialize(outFile, obj);
}
else { throw new FileNotFoundException("File not found", filename); }
}
}
My Testing Implementation:
BankDesign.Camt.Document document = new BankDesign.Camt.Document();
document.BkToCstmrStmt = new BkToCstmrStmt();
document.BkToCstmrStmt.GrpHdr = new BankDesign.Camt.GrpHdr(1233215, DateTime.UtcNow, new MsgPgntn(123546, false));
document.BkToCstmrStmt.Stmt = new Stmt();
document.BkToCstmrStmt.Stmt.Acct = new Acct();
AdrLine[] lines = new AdrLine[2];
AdrLine AdrLine = new AdrLine();
AdrLine.Name = "Test";
lines[0] = AdrLine;
AdrLine = new AdrLine();
AdrLine.Name = "Test2";
lines[1] = AdrLine;
document.BkToCstmrStmt.Stmt.Acct.Ownr = new Ownr("Test", new PstlAdr(lines));
FileManager.SaveAs<Document>(document, "Camt05300104", "urn:iso:std:iso:20022:tech:xsd:camt.053.001.04");
Camt05300104 Data:
<?xml version="1.0"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.04">
<BkToCstmrStmt>
<GrpHdr>
<MsgId>1233215</MsgId>
<CreDtTm>2023-02-07T10:57:07.2314082Z</CreDtTm>
<MsgPgntn>
<PgNb>123546</PgNb>
<LastPgInd>false</LastPgInd>
</MsgPgntn>
</GrpHdr>
<Stmt>
<Id>0</Id>
<ElctrncSeqNb>0</ElctrncSeqNb>
<CreDtTm>0001-01-01T00:00:00</CreDtTm>
<FrToDt>
<FrDtTm>0001-01-01T00:00:00</FrDtTm>
<ToDtTm>0001-01-01T00:00:00</ToDtTm>
</FrToDt>
<Acct>
<Id />
<Ownr>
<Nm>Test</Nm>
<PstlAdr>
<AdrLine><Name>Test</Name></AdrLine>
<AdrLine><Name>Test2</Name></AdrLine>
</PstlAdr>
</Ownr>
</Acct>
</Stmt>
</BkToCstmrStmt>
</Document>
The Camt Classes for Deserialize
//camt.053.001.04
namespace BankDesign.Camt
{
public struct PstlAdr
{
[XmlElement()]
public AdrLine[] AdrLine;
public PstlAdr(AdrLine[] adrLine)
{
AdrLine = adrLine;
}
}
public class AdrLine
{
public string Name { get; set; }
public AdrLine() { }
}
}

Seems i found a solution that worked for me.
public struct PstlAdr
{
[XmlElement()]
public AdrLine[] AdrLine;
public PstlAdr(AdrLine[] adrLine)
{
AdrLine = adrLine;
}
}
public class AdrLine
{
[XmlText()]
public string Name { get; set; }
public AdrLine() { }
}
Found at:
https://learn.microsoft.com/de-de/dotnet/api/system.xml.xmlelement?view=net-7.0 and
https://learn.microsoft.com/de-de/dotnet/api/system.xml.xmltext?view=net-7.0

Related

XML-Serialization - How to pass an property-array without it loosing its XML-Attributes

I have two classes. One of the classes is containing an array of the other class.
I dont want the first Class to be serialized, only the array of the other class, so I am passing the array to the Serialization-Method, but it seems to be loosing its name, as it is later called ArrayOfSecondClass. Can someone help me with this?
Here is some Test-Code describing the Scenario:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace TeaTimeTestEmpty
{
public class FirstClass
{
[XmlArray("RealName")] // Is ignored when SecondClassArray is passed
public SecondClass[] SecondClassArray { get; set; }
}
public class SecondClass
{
public string Name { get; set; }
}
public static class Program
{
public static string SerializeToXml(object objectToSerialize, Type objectType = null)
{
if (objectToSerialize != null)
{
if (objectType == null)
{
objectType = objectToSerialize.GetType();
}
XmlSerializer serializer = new XmlSerializer(objectType);
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, objectToSerialize, null);
string xmlString = "";
foreach (byte currentByte in stream.ToArray())
{
xmlString += (char)currentByte;
}
return xmlString;
}
}
return null;
}
static void Main(string[] args)
{
List<SecondClass> listOfSecondClasses = new List<SecondClass>();
for (int i = 0; i < 10; ++i)
{
listOfSecondClasses.Add(new SecondClass() { Name = "Bob" + i });
}
FirstClass firstClass = new FirstClass() { SecondClassArray = listOfSecondClasses.ToArray()};
// Note that I am passing only the SecondClassArray, not the whole Element
string xml = SerializeToXml(firstClass.SecondClassArray);
}
}
}
Now when I am debugging this, I get the following XML-Code in the variable xml:
<?xml version="1.0"?>
<ArrayOfSecondClass
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SecondClass>
<Name>Bob0</Name>
</SecondClass>
<SecondClass>
<Name>Bob1</Name>
</SecondClass>
<SecondClass>
<Name>Bob2</Name>
</SecondClass>
<SecondClass>
<Name>Bob3</Name>
</SecondClass>
<SecondClass>
<Name>Bob4</Name>
</SecondClass>
<SecondClass>
<Name>Bob5</Name>
</SecondClass>
<SecondClass>
<Name>Bob6</Name>
</SecondClass>
<SecondClass>
<Name>Bob7</Name>
</SecondClass>
<SecondClass>
<Name>Bob8</Name>
</SecondClass>
<SecondClass>
<Name>Bob9</Name>
</SecondClass>
</ArrayOfSecondClass>
My problem now is, that the Name I gave it in FirstClass is lost, and I cant seem to find a way to get it back, not even if I am giving the SecondClass XmlRoot or other tags, it is always calling it ArrayOfSecondClass instead of the wanted name.
I would appreciate it if you could give me a solution to how to give it the name I want it to have.
static void Main(string[] args)
{
List<SecondClass> listOfSecondClasses = new List<SecondClass>();
for (int i = 0; i < 10; ++i)
{
listOfSecondClasses.Add(new SecondClass() { Name = "Bob" + i });
}
FirstClass firstClass = new FirstClass() { SecondClassArray = listOfSecondClasses.ToArray() };
// Note that I am passing only the SecondClassArray, not the whole Element
string xml = SerializeToXml(firstClass.SecondClassArray,"RealNames");
Console.WriteLine(xml);
Console.ReadLine();
}
public static string SerializeToXml<T>(T objectToSerialize, string RootNodeName)
{
if (objectToSerialize != null)
{
XmlRootAttribute root = new XmlRootAttribute(RootNodeName);
XmlSerializer serializer = new XmlSerializer(typeof(T),root);
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, objectToSerialize, null);
string xmlString = "";
foreach (byte currentByte in stream.ToArray())
{
xmlString += (char)currentByte;
}
return xmlString;
}
}
return null;
}
The XmlArray attribute is part of FirstClass not of its property, so it is clear that it is not used when the serializer never sees an instance of FirstClass.
You will need to work with another constructor of the XmlSerializer class.
This constructor allows you to pass the name of the root element:
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "RealName";
XmlSerializer serializer = new XmlSerializer(objectType, xRoot);

C# - parse xml nodes

I am loading my data from XML using C# this way:
XmlDocument xmlDoc = new XmlDocument();
TextAsset xmlFile = Resources.Load("levels/" + levelID) as TextAsset;
xmlDoc.LoadXml(xmlFile.text);
XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level");
foreach (XmlNode levelInfo in levelsList)
{
XmlNodeList childNodes = levelInfo.ChildNodes;
foreach (XmlNode value in childNodes)
{
switch (value.Name)
{
case "info":
//levelWidth = getInt(value, 0);
//levelHeight = getInt(value, 1);
break;
}
}
}
And heres XML I am loading:
<?xml version="1.0" encoding="utf-8" ?>
<level>
<info w="1000" h="500"/>
</level>
It works just fine, I am now trying to find best way to load child nodes, inside my level node with multiple points nodes inside
<?xml version="1.0" encoding="utf-8" ?>
<level>
<info w="1000" h="500"/>
<ground>
<point val1="val1" val2="val2"/>
</ground>
</level>
I will be grateful for some guidance how to move in the right direction, thank you.
Using XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<level>" +
"<info w=\"1000\" h=\"500\"/>" +
"</level>";
XDocument doc = XDocument.Parse(xml);
XElement level = (XElement)doc.FirstNode;
level.Add("ground", new object[] {
new XElement("point", new XAttribute[] {
new XAttribute("val1", "val1"),
new XAttribute("val2", "val2")
})
});
}
}
}
​
If you need read all points, you can use
var nodeList = Xmldocument.SelectNodes("level/info/ground/point");
SelectNodes return a list of nodes.
I would go for a slidely different way and use a data object. Then you don't have to analyse xml, you just code your data class:
[Serializable()]
public class CLevel
{
public string Info { get; set; }
}
[Serializable()]
public class CDatafile
{
public List<CLevel> LevelList { get; set; }
public CDatafile()
{
LevelList = new List<CLevel>();
}
}
public class DataManager
{
private string FileName = "Data.xml";
public CDatafile Datafile { get; set; }
public DataManager()
{
Datafile = new CDatafile();
}
// Load file
public void LoadFile()
{
if (System.IO.File.Exists(FileName))
{
System.IO.StreamReader srReader = System.IO.File.OpenText(FileName);
Type tType = Datafile.GetType();
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
object oData = xsSerializer.Deserialize(srReader);
Datafile = (CDatafile)oData;
srReader.Close();
}
}
// Save file
public void SaveFile()
{
System.IO.StreamWriter swWriter = System.IO.File.CreateText(FileName);
Type tType = Datafile.GetType();
if (tType.IsSerializable)
{
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
xsSerializer.Serialize(swWriter, Datafile);
swWriter.Close();
}
}
Then you can use it to create, save and load the file like this:
DataManager dataMng = new DataManager();
// Create some data
CLevel level = new CLevel();
level.Info = "Testlevel";
dataMng.Datafile.LevelList.Add(level);
// Save to file
dataMng.SaveFile();
// Load from file
dataMng.LoadFile();
So you can do everything in code checked by the compiler. Makes life a lot easier, or what do you think?

how to remove default namespaces and add custom namespace in root tag of xml using C#?

While creating xml from C# class I getting some default namespaces(xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema") in root tag (Order) like below. but, I want to remove those default namespaces and I need the following namespace in the root tag (Order xmlns="http://example.com/xml/1.0").
how to remove those default namespaces and replace in c# code. thanks in advance.
<?xml version="1.0"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Number Type="mobile">9999999999</Number>
<TrackStartDateTime>2015-05-30 11:00 ET</TrackStartDateTime>
<Notifications>
<Notification>
<PartnerMPID>99999999</PartnerMPID>
<IDNumber>L563645</IDNumber>
<TrackDurationInHours>120</TrackDurationInHours>
<TrackIntervalInMinutes>240</TrackIntervalInMinutes>
</Notification>
</Notifications>
<Carrier>
<Dispatcher>
<DispatcherName>?</DispatcherName>
<DispatcherPhone>0</DispatcherPhone>
<DispatcherEmail>?</DispatcherEmail>
</Dispatcher>
</Carrier>
</Order>
I have used following C# classes.
[XmlRoot("Order")]
public class Order
{
[XmlElement("Number")]
public Number Number;
[XmlElement("TrackStartDateTime")]
public string TrackStartDateTime;//TODO - need to check
[XmlElement("Notifications")]
public Notifications Notifications;//TODO - notification tag should come inside Notifications tag
[XmlElement("Carrier")]
public Carrier Carrier;
public Order() {
Number = new Number();
Notifications = new Notifications();
Carrier = new Carrier();
TripSheet = new TripSheet();
}
}
public class Number
{
[XmlAttribute("Type")]
public string Type;
[XmlText]
public Int64 Value;
}
public class Notifications {
[XmlElement("Notification")]
public List<Notification> Notification;
public Notifications() {
Notification = new List<Notification>();
}
}
public class Notification
{
[XmlElement("PartnerMPID")]
public string PartnerMPID { get; set; }
[XmlElement("IDNumber")]
public string IDNumber { get; set; }
[XmlElement("TrackDurationInHours")]
public int TrackDurationInHours { get; set; }
[XmlElement("TrackIntervalInMinutes")]
public int TrackIntervalInMinutes { get; set; }
}
public class Carrier
{
[XmlElement("Name")]
public string Name;
[XmlElement("Dispatcher")]
public Dispatcher Dispatcher;
public Carrier() {
Dispatcher = new Dispatcher();
}
}
public class Dispatcher
{
[XmlElement("DispatcherName")]
public string DispatcherName;
[XmlElement("DispatcherPhone")]
public Int64 DispatcherPhone;
[XmlElement("DispatcherEmail")]
public string DispatcherEmail;//conform format for email
}
and I have taken the new instance of Order Class and for testing purpose, I have hard-coded values for the each fields and I have used the following code for the creating xml from the C# class.
public string CreateXML(Order order)
{
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Order));
// Creates a stream whose backing store is memory.
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, order);//,ns
xmlStream.Position = 0;
//Loads the XML document from the specified string.
xmlDoc.Load(xmlStream);
return xmlDoc.InnerXml;
}
}
I am not sure its a right approach for creating xml from C# classes. Please guide me to get the following xml output from c# class.
<?xml version="1.0"?>
<Order xmlns="http://example.com/xml/1.0" >
<Number Type="mobile">9999999999</Number>
<TrackStartDateTime>2015-05-30 11:00 ET</TrackStartDateTime>
<Notifications>
<Notification>
<PartnerMPID>99999999</PartnerMPID>
<IDNumber>L563645</IDNumber>
<TrackDurationInHours>120</TrackDurationInHours>
<TrackIntervalInMinutes>240</TrackIntervalInMinutes>
</Notification>
</Notifications>
<Carrier>
<Dispatcher>
<DispatcherName>?</DispatcherName>
<DispatcherPhone>0</DispatcherPhone>
<DispatcherEmail>?</DispatcherEmail>
</Dispatcher>
</Carrier>
</Order>
Here is a way to do it...
Just create a new XDocument and set the namespace that you want on it and transplant the original xml descendant into it, like so:
var xml = "<?xml version=\"1.0\"?><Order xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Number Type=\"mobile\">9999999999</Number></Order>";
var xdoc = XDocument.Parse(xml);
var ns = XNamespace.Get("http://example.com/xml/1.0");
var xdoc2 = new XDocument(new XDeclaration("1.0", null, null),
new XElement(ns + "Order", xdoc.Root.Descendants()));
See here for working sample: https://dotnetfiddle.net/JYCL95
For this case it should be sufficient to simply add a null namespace to the XMLRoot decoration used on your class definition.
[XmlRoot("Order", Namespace = null)]
public class Order
{
[XmlElement("Number")]
public Number Number;
[XmlElement("TrackStartDateTime")]
public string TrackStartDateTime;
[XmlElement("Notifications")]
public Notifications Notifications;
[XmlElement("Carrier")]
public Carrier Carrier;
The serializer should do the rest.

Deserialising XML without a declaration or namespace in Silverlight

I've been landed with a feed of XML data that I need to deserialise into objects in a Silverlight (v5) application. The data looks like:
<AgentState>
<agentName>jbloggs</agentName>
<extension>12345</extension>
<currentlyIn>TestStatus</currentlyIn>
</AgentState>
I've created a class at the Silverlight side, and I'm trying to get this XML - which, you'll notice, is missing a declaration and a namespace - into objects.
StringReader sr = null;
string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
sr = new StringReader(data);
XmlSerializer xs = new XmlSerializer(typeof (AgentState));
AgentState agent = (AgentState) xs.Deserialize(sr);
.. but this throws an error an error in xml document (1,2), as it's missing the declaration. Even manually adding a dummy declaration gives further errors about missing namespaces.
I've found other questions about ignoring namespace/declarations in XML, but none of these seem to work in Silverlight.
Can anyone advise on the best way to get this XML deserialised into an object?
This seems to work:
public class AgentState
{
public string agentName { get; set; }
public string extension { get; set; }
public string currentlyIn { get; set; }
}
static void Main(string[] args)
{
var s = #"<AgentState>
<agentName>jbloggs</agentName>
<extension>12345</extension>
<currentlyIn>TestStatus</currentlyIn>
</AgentState>";
XmlSerializer serializer = new XmlSerializer(typeof(AgentState));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(s));
var obj = serializer.Deserialize(ms);
}
I'm wondering what issue you have with appending the xml declaration to the string. This appears to work ok:
[System.Xml.Serialization.XmlRootAttribute("AgentState")]
public class AgentState
{
public string agentName {get; set;}
public int extension {get; set;}
public string currentlyIn {get; set;}
}
public void RunSerializer()
{
System.Xml.Serialization.XmlSerializer agent_serializer =
new System.Xml.Serialization.XmlSerializer(typeof(AgentState));
string agent_state_text = File.ReadAllText(#"C:\Temp\AgentState.xml");
Console.WriteLine(agent_state_text + Environment.NewLine);
string xml_agent_state = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + agent_state_text;
Console.WriteLine(xml_agent_state + Environment.NewLine);
AgentState agent_state = new AgentState();
using(StringReader tx_reader = new StringReader(xml_agent_state))
{
if (tx_reader != null)
{
agent_state = (AgentState)agent_serializer.Deserialize(tx_reader);
}
}
Console.WriteLine(agent_state.agentName);
Console.WriteLine(agent_state.extension);
Console.WriteLine(agent_state.currentlyIn);
}
Output:
<AgentState>
<agentName>jbloggs</agentName>
<extension>12345</extension>
<currentlyIn>TestStatus</currentlyIn>
</AgentState>
<?xml version="1.0" encoding="UTF-8"?>
<AgentState>
<agentName>jbloggs</agentName>
<extension>12345</extension>
<currentlyIn>TestStatus</currentlyIn>
</AgentState>
jbloggs
12345
TestStatus
I've managed to get it working using the following code - I'm not convinced it's the "right" way to do things, but it seems to work:
string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
var document = XDocument.Parse(data);
AgentState agent= (from c in document.Elements()
select new AgentState()
{
agentName = c.Element("agentName").Value,
extension = c.Element("extension").Value,
currentlyIn=c.Element("currentlyIn").Value
}).Single();
Thanks for the advice, it got me on the right track.

XML Serialize Example, first steps

I have following exercise to do ...
I shall get following xml-file ...
<?xml version="1.0" encoding="UTF-8"?>
<Mitarbeiterstatistik xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Mitarbeiter>
<Vorname>Horst</Vorname>
<Nachname>Schneider</Nachname>
<Id>1</Id>
</Mitarbeiter>
<Mitarbeiter>
<Vorname>Tanja</Vorname>
<Nachname>Lindner</Nachname>
<Id>2</Id>
</Mitarbeiter>
</Mitarbeiterstatistik>
Now I tried following steps ...
I made a class Mitarbeiter!
public class Mitarbeiter
{
private string vorname;
private string nachname;
private int id;
public Mitarbeiter()
{
}
public Mitarbeiter(string vorname, string nachname, int id)
{
this.vorname = vorname;
this.nachname = nachname;
this.id = id;
}
public string Vorname
{
get { return vorname; }
set { vorname = value; }
}
public string Nachname
{
get { return nachname; }
set { nachname = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
}
Then I made a class Mitarbeiterstatistik with a list for Mitarbeiter objects ...
[XmlRoot("Mitarbeiterstatistik")]
public class Mitarbeiterstatistik
{
private List<Mitarbeiter> list = new List<Mitarbeiter>();
[XmlArray("List")]
public List<Mitarbeiter> List
{
get { return list; }
set { list = value; }
}
}
My Main-Class looks like ...
class Program
{
static void Main(string[] args)
{
Mitarbeiterstatistik maStatistik = new Mitarbeiterstatistik();
Mitarbeiter ma1 = new Mitarbeiter("Horst", "Schneider", 1);
Mitarbeiter ma2 = new Mitarbeiter("Tanja", "Lindner", 2);
maStatistik.List.Add(ma1);
maStatistik.List.Add(ma2);
XmlSerializer serializer = new XmlSerializer(typeof(Mitarbeiterstatistik));
XmlWriter writer = XmlWriter.Create(#"D:\test.xml");
serializer.Serialize(writer, maStatistik);
writer.Close();
}
}
Now I got following result ...
<?xml version="1.0" encoding="UTF-8"?>
<Mitarbeiterstatistik xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
**<List>**
<Mitarbeiter>
<Vorname>Horst</Vorname>
<Nachname>Schneider</Nachname>
<Id>1</Id>
</Mitarbeiter>
<Mitarbeiter>
<Vorname>Tanja</Vorname>
<Nachname>Schneider</Nachname>
<Id>2</Id>
</Mitarbeiter>
**</List>**
</Mitarbeiterstatistik>
No I have an Element "List" in my Xml-file ... :-)
What can I do against my problem ...
Is there only the possibility to define only a Mitarbeiter class and NO Mitarbeiterstatistik-Class?
Maybe as following?
List<Mitarbeiter> list = new List<Mitarbeiter>();
Mitarbeiter ma1 = new Mitarbeiter("Horst", "Schneider", 1);
Mitarbeiter ma2 = new Mitarbeiter("Tanja", "Lindner", 2);
list.Add(ma1);
list.Add(ma2);
XmlSerializer serializer = new XmlSerializer(typeof(List<Mitarbeiter>), new XmlRootAttribute("Mitarbeiterstatistik"));
XmlWriter writer = XmlWriter.Create(#"D:\test.xml");
serializer.Serialize(writer, list);
writer.Close();
Or is there a chance to keep my Mitarbeiterstatistik-Class??? And disable my List-Element???
If you want to try Linq To Xml:
XDocument xDoc = new XDocument(new XElement("Mitarbeiterstatistik"));
foreach (var mitarbeiter in list)
{
xDoc.Root.Add(
new XElement("Mitarbeiter",
new XElement("Vorname" ,mitarbeiter.Vorname ),
new XElement("Nachname" ,mitarbeiter.Nachname ),
new XElement("Id" ,mitarbeiter.Id )));
}
xDoc.Save(#"d:\test.xml");
You can get out of attribute "List" (as i undestand your question correctly) using [XmlElement] with name of element you want to get instead of [XmlArray]:
[XmlRoot("Mitarbeiterstatistik")]
public class Mitarbeiterstatistik
{
private List<Mitarbeiter> list = new List<Mitarbeiter>();
[XmlElement("Mitarbeiter")]
public List<Mitarbeiter> List {get; set;}
}

Categories

Resources