How to Map Xml to C# Objects

How to map XML file content to C# object(s)

It sounds like you want use XML serialization. There is a lot already out there, but this is a pretty simple example.
http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

The snippet you want is about 1/4 of the way down:

XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
TextReader textReader = new StreamReader(@"C:\movie.xml");
List<Movie> movies;
movies = (List<Movie>)deserializer.Deserialize(textReader);
textReader.Close();

Hopefully, this helps

How to map xml objects into listelements in c#?

There are many ways to map xml, one is using built-in .NET XML serializer. Here is one way to serialize it.

SecretModel

[XmlRoot(ElementName = "SecretModel")]
public class SecretModel
{
[XmlAttribute(AttributeName = "id")]
public int Id { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "secretTemplateId")]
public string SecretTemplateId { get; set; }
[XmlAttribute(AttributeName = "folderId")]
public string FolderId { get; set; }
[XmlAttribute(AttributeName = "active")]
public bool Active { get; set; }
[XmlElement(ElementName = "items")]
public List<RestSecretItem> Items { get; set; }
}

RestSecretItem

[XmlRoot(ElementName = "items")]
public class RestSecretItem
{
[XmlAttribute(AttributeName = "itemId")]
public int ItemId { get; set; }
[XmlAttribute(AttributeName = "fileAttachmentId")]
public int FileAttachmentId { get; set; }
[XmlAttribute(AttributeName = "filename")]
public string FileName { get; set; }
[XmlAttribute(AttributeName = "itemValue")]
public string ItemValue { get; set; }
[XmlAttribute(AttributeName = "fieldId")]
public int FieldId { get; set; }
[XmlAttribute(AttributeName = "fieldName")]
public string FieldName { get; set; }
[XmlAttribute(AttributeName = "slug")]
public string Slug { get; set; }
[XmlAttribute(AttributeName = "fieldDescription")]
public string FieldDescription { get; set; }
[XmlAttribute(AttributeName = "isFile")]
public bool IsFile { get; set; }
[XmlAttribute(AttributeName = "isNotes")]
public bool IsNote { get; set; }
[XmlAttribute(AttributeName = "isPassword")]
public bool IsPassword { get; set; }
}

Now you can parse the xml through using this code:

var doc = new XmlDocument();
doc.load("your directory or path of file here");
using(var reader = new StringReader(doc.InnerXml))
{
var serializer = new XmlSerializer(typeof(SecretModel));
var data = (SecretModel)serializer.Deserialize(reader); // converted model here
}

How do I map XML to C# objects

You can generate serializable C# classes from a schema (xsd) using xsd.exe:

xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir

If the schema has dependencies (included/imported schemas), they must all be included on the same command line.

Map XML tags with dot(.) to C# object

I have pasted your XML in an XMLFile1.xml and pasted it in Visual Studio to generate classes, so this will be a lot of autogenerated code... warning

could not fit auto gen code...

Body is limited to 30000 characters; you entered 93977

Full code here:
https://pastebin.com/VxzNUjsv

Smaller version:

<?xml version="1.0" encoding="UTF-8"?>
<customer>
<RECORDNO>5</RECORDNO>
<CUSTOMERID>CUST-00101</CUSTOMERID>
<PARENTNAME>parent</PARENTNAME>
<DISPLAYCONTACT.CONTACTNAME>Sun Microsystems - EBC(CCUST-00101)</DISPLAYCONTACT.CONTACTNAME>
<DISPLAYCONTACT.COMPANYNAME>Sun Microsystems - EBC</DISPLAYCONTACT.COMPANYNAME>
</customer>

and C# code:

class Program
{
static void Main(string[] args)
{

using (var sreader = new StringReader(File.ReadAllText(@"C:\Users\JP\source\repos\soXmlParsing\soXmlParsing\XMLFile1.xml")))
using (var reader = XmlReader.Create(sreader))
{
var serializer = new XmlSerializer(typeof(customer));
var test = (customer)serializer.Deserialize(reader);
Console.WriteLine(test.PARENTNAME);
Console.WriteLine(test.DISPLAYCONTACTCONTACTNAME);
}
}
}

// 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 customer
{

private byte rECORDNOField;

private string cUSTOMERIDField;

private string pARENTNAMEField;

private string dISPLAYCONTACTCONTACTNAMEField;

private string dISPLAYCONTACTCOMPANYNAMEField;

/// <remarks/>
public byte RECORDNO
{
get
{
return this.rECORDNOField;
}
set
{
this.rECORDNOField = value;
}
}

/// <remarks/>
public string CUSTOMERID
{
get
{
return this.cUSTOMERIDField;
}
set
{
this.cUSTOMERIDField = value;
}
}

/// <remarks/>
public string PARENTNAME
{
get
{
return this.pARENTNAMEField;
}
set
{
this.pARENTNAMEField = value;
}
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DISPLAYCONTACT.CONTACTNAME")]
public string DISPLAYCONTACTCONTACTNAME
{
get
{
return this.dISPLAYCONTACTCONTACTNAMEField;
}
set
{
this.dISPLAYCONTACTCONTACTNAMEField = value;
}
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DISPLAYCONTACT.COMPANYNAME")]
public string DISPLAYCONTACTCOMPANYNAME
{
get
{
return this.dISPLAYCONTACTCOMPANYNAMEField;
}
set
{
this.dISPLAYCONTACTCOMPANYNAMEField = value;
}
}
}

How to map XML document to entity framework object?

Everything is said in :

Cannot serialize member
Proj.Accounting.Entity.DocumentStatus.Documents
of type

System.Collections.Generic.ICollection1[[Proj.Accounting.Entity.Document,
Proj.Accounting.Entity, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]] because it is an interface

Interface are not serializable. Transform all your ICollection properties to type HashSetto enable serialization of these items.

How to properly map XML content to DTO property in C#

Sometimes these (de)serializers need a little nudge in the right direction in order to get the right data into your objects. While JSON is loosely structured, XML files tend to have more stricter structures. Not necessarily by design, but by use.

As you already know judging by your code sample, you can prepend attributes to your objects and object properties which tell the XML serializer what to look for in the XML for that particular property.

Embedded objects can also contain instructions for the XML serializers. So prepending your embedded object's properties with attributes like [XmlAttribute("IsDefault")] (telling the XML serializer to look for an XML element's attribute "IsDefault" if it exists) and [XmlText] (telling the XML serializer to grab the text inside the XML element) will make life easier for XMLSerializer.

Not only does this make it clear to both you and XMLSerializer what it's looking for, it can also increase the performance of the search, as this prevents XMLSerializer to blindly start querying all possible places where your property could reside.



Related Topics



Leave a reply



Submit