Read XML file parse it into a class list - c#

This is the code that I've used to write the data from the List to the XML file:
using (FileStream f = new FileStream(#"animals.xml", FileMode.Create, FileAccess.Write))
{
var dcsw = new DataContractSerializer(typeof(List<Animal>));
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(f);
try
{
dcsw.WriteObject(f, animalList);
writer.Close();
f.Close();
return true;
}
catch (Exception)
{
return false;
}
This is an example of my XML file:
<ArrayOfAnimal xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AnimalShelter">
<Animal i:type="Cat">
<ChipRegistrationNumber>12346</ChipRegistrationNumber>
<DateOfBirth>
<date>1234-11-11T00:00:00</date>
</DateOfBirth>
<IsReserved>false</IsReserved>
<Name>Yoshi</Name>
<BadHabits>Scratches</BadHabits>
<Price>51</Price>
</Animal>
<Animal i:type="Dog">
<ChipRegistrationNumber>12347</ChipRegistrationNumber>
<DateOfBirth>
<date>1234-11-11T00:00:00</date>
</DateOfBirth>
<IsReserved>false</IsReserved>
<Name>Sonic</Name>
<LastWalkDate>
<date>1234-11-11T00:00:00</date>
</LastWalkDate>
<Price>200</Price>
</Animal>
</ArrayOfAnimal>
As you can see, Cat has a a node called "BadHabits" and Dog has a different one called "LastWalkDate".
"Cat" and "Dog" inherit from the class Animal.
I've seen many examples of parsing strings to a List.. That's quite do-able.. but my list has different types like a custom date class
Example of an instance of Animal:
SimpleDate date1 = new SimpleDate(11, 11, 1234);
Animal cat1 = new Cat("12346", date1, "Yoshi", "Scratches");
How am I able to parse all the cats and dogs from the XML file in a List<Animal>?

You can probably use something like this:
using (FileStream f = new FileStream(<pathtoxml>, FileMode.Open, FileAccess.Read))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<Animal>));
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(f, new XmlDictionaryReaderQuotas());
List<Animal> listfromxml = (List<Animal>)dcs.ReadObject(reader);
}

Here is your class related to your XML file.
Generated with this tools
EDIT : you have an invalid XML near from the "Price" element : <Price>51</rice>
[XmlRoot(ElementName="DateOfBirth", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public class DateOfBirth {
[XmlElement(ElementName="date", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string Date { get; set; }
}
[XmlRoot(ElementName="Animal", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public class Animal {
[XmlElement(ElementName="ChipRegistrationNumber", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string ChipRegistrationNumber { get; set; }
[XmlElement(ElementName="DateOfBirth", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public DateOfBirth DateOfBirth { get; set; }
[XmlElement(ElementName="IsReserved", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string IsReserved { get; set; }
[XmlElement(ElementName="Name", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string Name { get; set; }
[XmlElement(ElementName="BadHabits", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string BadHabits { get; set; }
[XmlElement(ElementName="Price", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string Price { get; set; }
[XmlAttribute(AttributeName="type", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
[XmlElement(ElementName="LastWalkDate", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public LastWalkDate LastWalkDate { get; set; }
}
[XmlRoot(ElementName="LastWalkDate", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public class LastWalkDate {
[XmlElement(ElementName="date", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public string Date { get; set; }
}
[XmlRoot(ElementName="ArrayOfAnimal", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public class ArrayOfAnimal {
[XmlElement(ElementName="Animal", Namespace="http://schemas.datacontract.org/2004/07/AnimalShelter")]
public List<Animal> Animal { get; set; }
[XmlAttribute(AttributeName="i", Namespace="http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}

Related

XML deserialization returns list with one empty item

I have the following XML:
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<accounts>
<items>
<account>
<voornaam><FirstName</voornaam>
<naam>LastName</naam>
<gebruikersnaam>Username</gebruikersnaam>
<internnummer></internnummer>
<klasnummer></klasnummer>
</account>
</items>
</accounts>
With these classes:
public class Accounts
{
public Accounts()
{
items = new List<Account>();
}
[XmlElement]
public List<Account> items { get; set; }
}
public class Account
{
public string voornaam { get; set; }
public string naam { get; set; }
public string gebruikersnaam { get; set; }
public int? internnummer { get; set; }
public int? klasnummer { get; set; }
}
And this code:
var decoded = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><accounts><items><account><voornaam>FirstName</voornaam><naam>LastName</naam><gebruikersnaam></gebruikersnaam><internnummer></internnummer><klasnummer></klasnummer></account></items></accounts>";
XmlSerializer serializer = new XmlSerializer(typeof(Accounts), new XmlRootAttribute("accounts"));
StringReader reader = new StringReader(decoded);
var accounts = (Accounts)serializer.Deserialize(reader);
All I get from this is an Accounts instance with the property Items containing one Account instance with every property null.
You need to specify the items as XML array with XmlArrayAttribute and also with the XmlArrayItemAttribute with (element) item's name: "account" and as Account type. XmlArrayAttribute Example.
public class Accounts
{
[XmlArrayItem(ElementName= "account",
Type = typeof(Account))]
[XmlArray(ElementName="items")]
public List<Account> items { get; set; }
}
Meanwhile, suggest using XmlElementAttribute to specify the element name in XML instead of naming the properties as camelCase.
For the reason why need InternnummerText and KlasnummerText properties you can refer to the question: Deserializing empty xml attribute value into nullable int property using XmlSerializer (will not cover in this answer).
public class Accounts
{
public Accounts()
{
Items = new List<Account>();
}
[XmlArrayItem(ElementName= "account",
Type = typeof(Account))]
[XmlArray(ElementName="items")]
public List<Account> Items { get; set; }
}
[XmlRoot(ElementName="account")]
public class Account
{
[XmlIgnore]
public int? Klasnummer { get; set; }
[XmlIgnore]
public int? Internnummer { get; set; }
[XmlElement(ElementName="voornaam")]
public string Voornaam { get; set; }
[XmlElement(ElementName="naam")]
public string Naam { get; set; }
[XmlElement(ElementName="gebruikersnaam")]
public string Gebruikersnaam { get; set; }
[XmlElement(ElementName="internnummer")]
public string InternnummerText
{
get { return (Internnummer.HasValue) ? Internnummer.ToString() : null; }
set { Internnummer = !string.IsNullOrEmpty(value) ? int.Parse(value) : default(int?); }
}
[XmlElement(ElementName="klasnummer")]
public string KlasnummerText
{
get { return (Klasnummer.HasValue) ? Klasnummer.ToString() : null; }
set { Klasnummer = !string.IsNullOrEmpty(value) ? int.Parse(value) : default(int?); }
}
}
Sample program

c# - Get data tree from XML file

I have an XML file which has many children:
<Docs>
<Doc>
<DocType>x</DocType>
<DocNumber>xxx</DocNumber>
<DocNumberSeries>xx</DocNumberSeries>
<DocDate>xxxx-xx-xx</DocDate>
<DocCause>
<Id>xx</Id>
<Code/>
<Name>xx</Name>
</DocCause>
<Anag>
<Name>NameCompany</Name>
<Address>xx</Address>
<ZipCode>xx</ZipCode>
<City>xx</City>
<Province>xx</Province>
<CountryCode>xx</CountryCode>
<PhoneNumber>xx</PhoneNumber>
<CellularNumber/>
<FaxNumber>xx</FaxNumber>
<EmailAddress>xx</EmailAddress>
<VatNumber>xx</VatNumber>
<PersonalID>xx</PersonalID>
</Anag>
<DestinationAddress>
<Name>xxL</Name>
<Address>xx</Address>
<ZipCode>xx</ZipCode>
<City>xx</City>
<Province>xx</Province>
<CountryCode>xx</CountryCode>
<PhoneNumber>xx</PhoneNumber>
<FaxNumber>xx</FaxNumber>
</DestinationAddress>
<Payment>
<Code/>
<Name>xx</Name>
</Payment>
<DocRows>
<DocRow>
<RowType>1</RowType>
<Product>
<Code>LSML1710</Code>
</Product>
<Description></Description>
<Quantity></Quantity>
<Price></Price>
<Tax>
<Tax>
<Id>xx</Id>
<Code/>
<Name>xx</Name>
<PercentAmount>xx</PercentAmount>
<IndPercentAmount>x</IndPercentAmount>
<FixedAmount>x</FixedAmount>
</Tax>
</Tax>
</DocRow>
</DocRows>
...
</Doc>
For example, one of the thing I want to do is to get the data inside tag Doc and then Anag.
At the moment I have these classes:
public class Anag
{
public string RagioneSociale { get; set; }
public string Indirizzo { get; set; }
public string CAP { get; set; }
public string Citta { get; set; }
public string Provincia { get; set; }
public string CodiceNazione { get; set; }
public string Telefono { get; set; }
public string Cellulare { get; set; }
public string Email { get; set; }
}
public class Doc
{
public string DocNumber { get; set; }
public Anag Anags { get; set; }
}
List<Doc> results = contentFile.Descendants("Doc").Select(doc => new Doc // var results = contentFile.Descendants("Doc").SelectMany(doc => doc.Descendants(doc.Name.Namespace + "Anag").Select(anag => new
{
DocNumber = (string)doc.Element(doc.Name.Namespace + "DocNumber"),
Anags = doc.Descendants(doc.Name.Namespace + "Anag").Select(anag => new Anag
{
RagioneSociale = (string)anag.Element(anag.Name.Namespace + "Name"),
Indirizzo = (string)anag.Element(anag.Name.Namespace + "Address"),
CAP = (string)anag.Element(anag.Name.Namespace + "ZipCode"),
Provincia = (string)anag.Element(anag.Name.Namespace + "Province"),
Telefono = (string)anag.Element(anag.Name.Namespace + "PhoneNumber"),
Cellulare = (string)anag.Element(anag.Name.Namespace + "CellularNumber"),
Email = (string)anag.Element(anag.Name.Namespace + "EmailAddress"),
Citta = (string)anag.Element(anag.Name.Namespace + "City")
}),
}).ToList();
This last code gives an error:
Cannot implicitly convert type system.collections.generic.IEnumerable<nameProject.Classes.Anag> in <NameProject.Classes.Anag>.
The final result I want is a List with the data and children of this XML:
List:
+ Doc=>
{DocNumber}
+ Anag => { Address .. , Name.. .. ) (not a list ! )
+ DestinationAddress => { Address.... Name..)
so that I can convert to a file .csv only .
Since you already went through the trouble of creating the classes, why not let the deserializer do the job for you?
Here's how:
XmlSerializer serializer = new XmlSerializer(typeof(Root));
using (var reader = new StreamReader(xmlFilePath))
{
List<Doc> docs = ((Root)serializer.Deserialize(reader)).Docs;
}
Now, you just have to add some tags into your class properties so that they match the xml names.
[Serializable, XmlRoot("Docs")]
public class Root
{
[XmlElement("Doc")]
public List<Doc> Docs { get; set; }
}
public class Doc
{
public string DocNumber { get; set; }
[XmlElement("Anag")]
public Anag Anags { get; set; }
}
public class Anag
{
[XmlElement("Name")]
public string RagioneSociale { get; set; }
[XmlElement("Address")]
public string Indirizzo { get; set; }
[XmlElement("ZipCode")]
public string CAP { get; set; }
[XmlElement("City")]
public string Citta { get; set; }
[XmlElement("Province")]
public string Provincia { get; set; }
[XmlElement("CountryCode")]
public string CodiceNazione { get; set; }
[XmlElement("PhoneNumber")]
public string Telefono { get; set; }
[XmlElement("CellularNumber")]
public string Cellulare { get; set; }
[XmlElement("EmailAddress")]
public string Email { get; set; }
}
Just try using the feature "Paste Special" to generate the classes for parsing. You will 100% not get an exception.
Crtl + A on the whole xml, copy to clipboard
Then create a new class
in your project Click "Edit" -> "Paste Special" -> "Paste XML as
classes"
Change the parsing to use type of the "RootNode" in the
pasted class
Build and try it out.

How to Deserialize XMLElement with same name

I have XML root element and XML Element with same name, I am not sure how I should change my model class
The following code works as far as XML Element is not repeated with same name, in my case Gender list=1
Changing XML out format is not possible as it is coming from another system, unless filter out in C# code level
XML
<?xml version="1.0"?>
<Gender>
<Gender list="1">
<Item>
<CODE>M</CODE>
<DESCRIPTION>Male</DESCRIPTION>
</Item>
<Item>
<CODE>F</CODE>
<DESCRIPTION>Female</DESCRIPTION>
</Item>
</Gender>
</Gender>
Model Class
public class Gender
{
[XmlElement("Item")]
public List<Item> GenderList = new List<Item>();
}
public class Item
{
[XmlElement("CODE")]
public string Code { get; set; }
[XmlElement("DESCRIPTION")]
public string Description { get; set; }
}
XML Parsing Class
public static class XMLPrasing
{
public static Object ObjectToXML(string xml, Type objectType)
{
StringReader strReader = null;
XmlSerializer serializer = null;
XmlTextReader xmlReader = null;
Object obj = null;
try
{
strReader = new StringReader(xml);
serializer = new XmlSerializer(objectType);
xmlReader = new XmlTextReader(strReader);
obj = serializer.Deserialize(xmlReader);
}
catch (Exception exp)
{
//Handle Exception Code
var s = "d";
}
finally
{
if (xmlReader != null)
{
xmlReader.Close();
}
if (strReader != null)
{
strReader.Close();
}
}
return obj;
}
SECOND UPDATE
If I change my code with different Gender name as following then this work, question remain same how to handle with same name
<?xml version="1.0"?>
<Gender>
<GenderX list="1">
<Item>
<CODE>M</CODE>
<DESCRIPTION>Male</DESCRIPTION>
</Item>
<Item>
<CODE>F</CODE>
<DESCRIPTION>Female</DESCRIPTION>
</Item>
</GenderX>
</Gender>
Model class
[XmlRoot("Gender")]
public class Gender
{
[XmlElement("GenderX")]
public List<GenderX> GenderXList = new List<GenderX>();
}
public class GenderX
{
[XmlElement("Item")]
public List<Item> GenderList = new List<Item>();
}
public class Item
{
[XmlElement("CODE")]
public string Code { get; set; }
[XmlElement("DESCRIPTION")]
public string Description { get; set; }
}
I have found answer
[XmlRoot("Gender")]
public class Gender
{
[XmlElement("Gender")]
public List<GenderListWrap> _GenderListWrap = new List<GenderListWrap>();
}
public class GenderListWrap
{
[XmlAttribute("list")]
public string _ListTag { get; set; }
[XmlElement("Item")]
public List<Item> _GenderList = new List<Item>();
}
public class Item
{
[XmlElement("CODE")]
public string Code { get; set; }
[XmlElement("DESCRIPTION")]
public string Description { get; set; }
}
If you have only one top level Gender element, then this is enough:
[XmlRoot(ElementName = "Gender")]
public class Genders
{
[XmlElement(ElementName = "Gender")]
public Gender gender { get; set; }
}
public class Gender
{
[XmlElement(ElementName = "Item")]
public List<Item> GenderList = new List<Item>();
}
public class Item
{
[XmlElement("CODE")]
public string Code { get; set; }
[XmlElement("DESCRIPTION")]
public string Description { get; set; }
}
I'm using Generic method for deserialize XMLString.
This method take xml string and deserialized sender model Type.
You must use Model deserialized xml to property like this , and You should not forget to write [Serializable] for class attribute and [XmlElement] for property attribute
[Serializable]
public class Gender
{
[XmlElement("Item")]
public List<Item> GenderList = new List<Item>();
}
public class Item
{
[XmlElement("CODE")]
public string Code { get; set; }
[XmlElement("DESCRIPTION")]
public string Description { get; set; }
}
public static T Deserialize<T>(string input) where T : class
{
Log.Debug("Deserialize" + typeof(T).Name, "xml string Deserialize ediliyor" + Environment.NewLine + input);
XmlSerializer ser = new XmlSerializer(typeof(T), "SetDefaultNamespace"); // optinal parameters DefaultNamespace
using (StringReader sr = new StringReader(input))
{
var desearializedObject = (T)ser.Deserialize(sr);
Log.Debug("Deserialize" + typeof(T).Name, "Obje Deserialize işlemi tamamlandı");
return desearializedObject;
}
}
Deserialize<Gender>(xmlString);

Deserialize XML into Entitylist using C# from XMLdocument

Refer the below XML File with multiple event nodes into parent events tag
<events>
<event eventid="ahjy67kl" sessionid="1">
<eventtitle>
<![CDATA[ phoneEventchad_1 ]]>
</eventtitle>
<eventabstract/>
<timezone>IND</timezone>
<eventtimedate>Wed, 24 Jun 2015 06:00 PDT</eventtimedate>
<archivestartdate>Wed, 24 Jun 2015 09:30 PDT</archivestartdate>
<archiveenddate>Thu, 23 Jun 2016 09:30 PDT</archiveenddate>
<length>195</length>
<sponsor/>
<keywords/>
<location/>
<eventprofile>
<![CDATA[ Stonehenge Profile (918) ]]>
</eventprofile>
<streamtype>
<![CDATA[ whitepaper ]]>
</streamtype>
<categories/>
<eventstdfield1>
<value/>
</eventstdfield1>
<eventstdfield2/>
<eventstdfield3/>
<eventstdfield4/>
<eventstdfield5/>
<audiencekeylock>
<![CDATA[ 770D14C9CC784E9D9D312563B093E9A5 ]]>
</audiencekey>
<urls>
<audienceurl>
<![CDATA[
http://event.on24.com/wcc/r/1012538/770D14C9CC784E9D9D312563B093E9A5&partnerref=rss-scribev3
]]>
</audienceurl>
<extaudienceurl/>
<reporturl>
<![CDATA[ ##REPORT_URL## ]]>
</reporturl>
<uploadurl>
<![CDATA[ ##UPLOAD_URL## ]]>
</uploadurl>
<presenterurl>
<![CDATA[ ##PRESENTER_URL## ]]>
</presenterurl>
</urls>
<speakers/>
<registrationstats>
<registrantcount>0</registrantcount>
</registrationstats>
<attendancestats>
<attendedcount>0</attendedcount>
<noshowcount>0</noshowcount>
<attendedlivecount>0</attendedlivecount>
<attendedarchivecount>0</attendedarchivecount>
</attendancestats>
<partnerrefstats/>
<tags/>
<registrants></registrants>
<attendees></attendees>
</event>
</events>
"
Entity Class
public class events
{
private Event _event;
[XmlElement(ElementName = "event")]
public Event Event
{
get
{
return this._event;
}
set
{
this._event = value;
}
}
}
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Event
{
public string eventid { get; set; }
public string sessionid { get; set; }
public string eventTitle { get; set; }
public DateTime archivestartdate { get; set; }
public DateTime archiveenddate { get; set; }
public string eventabstract { get; set; }
public DateTime eventtimedate { get; set; }
public string eventprofile { get; set; }
public string registrantcount { get; set; }
public string sponsor { get; set; }
public string keywords { get; set; }
public string eventstdfield1 { get; set; }
public string eventstdfield2 { get; set; }
public string eventstdfield3 { get; set; }
public string eventstdfield4 { get; set; }
public string eventstdfield5 { get; set; }
public attendancestats attendancestats { get; set; }
public registrationstats registrationstats { get; set; }
public Event()
{ }
}
public class attendancestats
{
public string attendedcount { get; set; }
public string noshowcount { get; set; }
public string attendedlivecount { get; set; }
public string attendedarchivecount { get; set; }
}
public class registrationstats
{
public string registrantcount { get; set; }
}
I used below code to deserlize the menioned XML into above Entity class
pDoc is the object of XMLdocument filled with above xml
System.Xml.Serialization.XmlRootAttribute xRoot = new System.Xml.Serialization.XmlRootAttribute();
xRoot.ElementName = "events";
xRoot.IsNullable = true;
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<events>),xRoot);
XDocument Doc = new XDocument();
Doc = XDocument.Parse(pDoc.OuterXml);
//System.Xml.XmlReader reader = Doc.CreateReader();
XmlReader reader = XmlReader.Create(new System.IO.StringReader(Doc.ToString()));
List<Event> result = (List<Event>)serializer.Deserialize(reader);
reader.Close();
In above code reader object is getting null due to which result object of List is throwing exception.
I want the List of Events.
Please help me to achieve list of events. let me know if need to provide further details.
I can't really see how this could work. Your Event class seems to have only one event, XML file contains many Events. Try this:
[Serializable]
[XmlRoot(ElementName = "events")]
public class Events {
public Events()
{
EventList = new List<Event>();
}
[XmlElement(ElementName="event")]
List<Event> EventList {get; set;}
}
[Serializable]
public class Event {
[XmlAttribute("eventid")
public string eventid {get; set;}
.......
[XmlElement(ElementName="timezone")]
public string timezone {get; set;}
}
It is clear, you need to do that way with every available property. Now, deserialization:
string input = System.IO.File.ReadAllText(PATH_TO_YOUR_XML_FILE); //this can be replaced with any func giving string
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Events));
var doc = XDocument.Parse(input);
using (var reader = doc.Root.CreateReader())
{
return (Events)xmlSerializer.Deserialize(reader);
}
Okay, this will produce Events class, with List in EventList. Hope this helps.

Problem creating XML using c#

I am searching a batter solution for creating xml through xml serialization. What i need, i have a given format like this
<product Id="1">
<name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name>
<notes>
<note>!--note 1---</note>
<note>!--note 2--</note>
......
</notes>
</product>
what i am doing here, i created a 2 classes like this
public class product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<notes> ListNotes { get; set; }
}
public class notes
{
[XmlIgnore]
public string Note { get; set; }
}
when i am serializing this then i am getting xml in this formate
<product Id="1">
<name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name>
<notes>
<notes>
<note>!--note 1---</note>
<note>!--note 2--</note>
</notes>
</notes>
</product>
i don't want extra <notes>. Any batter solution to solve this problem?
Thanks
Solution
public class product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<notes> ListNotes { get; set; }
}
public class notes
{
[XmlText]
public string Note { get; set; }
}
product ObjProduct = new product
{
Name ="Pankaj",
notes=new List<note>()
}
foreach (var note in item.ListNote)
{
ObjProduct.notes.Add(new Highmark.BLL.Common.note { Note = EncodeTo64(note.Note) });
}
Now use this ObjProduct for serialization.
Try like this:
[XmlRoot("product")]
public class Product
{
[XmlAttribute]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("note")]
public List<Note> ListNotes { get; set; }
}
public class Note
{
[XmlText]
public string Text { get; set; }
}
class Program
{
public static void Main()
{
var p = new Product
{
Id = 1,
Name = "2 1/2 X 6 PVC NIPPLE TOE SCH 80",
ListNotes = new List<Note>
{
new Note { Text = "!--note 1---" },
new Note { Text = "!--note 2---" },
}
};
var serializer = new XmlSerializer(p.GetType());
serializer.Serialize(Console.Out, p);
}
}
And if you want to remove the namespace from the root node:
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(Console.Out, p, ns);
Try like this:
class Program
{
static void Main(string[] args)
{
var product = new Product() { Name = "PVC SCHOOL" };
product.Notes = new List<note>();
product.Notes.Add(new note() { Note = "A" });
product.Notes.Add(new note() { Note = "B" });
var serialer = new XmlSerializer(typeof(Product));
using (var stream = new StreamWriter("test.txt"))
{
serialer.Serialize(stream, product);
}
}
}
public class Product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("notes")]
public List<note> Notes { get; set; }
}
public class note
{
[XmlIgnore]
public string Note { get; set; }
}
This doesn't directly answer your question, but if you can't figure out this problem, you can create a Schema.xsd file, and use .NET's XSD tool to generate the proper serialization classes for you.
I've had pretty good success with that.
The obvious benefit of using a schema is the validation on XML, prior to serialization.

Categories