Click here to Skip to main content
15,898,820 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
i have an xml like below

<Parents>
<parent>
<child1>001</Child1>
<child2>Name1</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>002</Child1>
<child2>Name2</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>003</Child1>
<child2>Name3</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
<parent>
<child1>004</Child1>
<child2>Name4</Child2>
<child3>Address1</Child3>
<child4>Address2</Child4>
</parent>
</Parents>


and have a class in C# as below

public class xmldata
{
private string child1{get;set;}
private string child2{get;set;}
private string child3{get;set;}
private string child4{get;set;}
}


i want to read and assign all the xml elemet values to list of class like below

List<xmldata> data1 = new List<xmldata>();


this list should have all the four parent element values.

What I have tried:

i have tried to read the xml with Xdocument (LinQ) getting error and unable to achieve it.
Posted
Updated 24-May-19 11:56am

You can use this trick in Visual Studio 2017:

Goto Edit menu
Select 'Paste special'
Select 'Paste XML as classes'

Make sure everything has the same case, file name 'MyChildren.xml':
<parent>
<child1>001</child1>
<child2>name1</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>002</child1>
<child2>name2</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>003</child1>
<child2>name3</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>
<parent>
<child1>004</child1>
<child2>name4</child2>
<child3>address1</child3>
<child4>address2</child4>
</parent>


Example usage Form:
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.Serialization;

    public partial class Form1 : Form
    {
        /// <summary>
        /// The config for XML serialization.
        /// </summary>
        private Children childrenXml;

        public Form1()
        {
            this.InitializeComponent();
			this.SettingsRead("MyChildren.xml")
		}

        private bool SettingsRead(string fileNameFull)
        {
            bool result = false;

            try
            {
                var serializer = new XmlSerializer(this.childrenXml.GetType());
                string str = File.ReadAllText(fileNameFull);

                using (TextReader reader = new StringReader(str))
                {
                    this.childrenXml = (Children)serializer.Deserialize(reader);
                }

                result = true;
            }
            catch (Exception ex)
            {
                Debug.Print("SettingsRead() " + ex.Message);
            }

            return result;
        }
}

Class file:
C#
namespace MyChildren
{
    using System.Collections.Generic;

    public class Children
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Children"/> class.
        /// </summary>
        public Children()
        {
            this.ChildrenItemList = new List<ChildrenItem>();
        }
		
		/// <summary>
        /// Gets or sets the ChildrenItemList
        /// </summary>
        public List<ChildrenItem> ChildrenItemList { get; set; }
    }

    /// <summary>
    /// ChildrenItem subclass defines one element in the Children.
    /// </summary>
    public class ChildrenItem
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ChildrenItem"/> class.
        /// </summary>
        public ChildrenItem()
        {
            // Only needed for serializer.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChildrenItem"/> class.
        /// </summary>
        public ChildrenItem(string c1, string c2, string c3, string c4)
        {
            this.Child1 = c1;
            this.Child2 = c2;
            this.Child3 = c3;
            this.Child4 = c4;
        }

        /// <summary>
        /// Gets or sets the Child(s)
        /// </summary>
        public string Child1 { get; set; }
		
		public string Child2 { get; set; }

		public string Child3 { get; set; }

		public string Child4 { get; set; }
	}
}
 
Share this answer
 
v4
Google this: c# deserialize nested xml
 
Share this answer
 
Comments
Member 10738387 28-May-19 5:38am    
thanks its working, i can able to deserialize and convert into objects

What I suggest you do is to download the Nuget package ExtendedXmlSerializer. Instantiate a List<XmlData> and Serialize it using the Serializer, then examine the output.

C#
List<XmlData> parents = new List<XmlData>
{
    new XmlData{child1="A1",child2="A2",child3="A3"},
    new XmlData{child1="B1",child2="B2",child3="B3"},
    new XmlData{child1="C1",child2="C2",child3="C3"}
};
   IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
   var xml = serializer.Serialize(parents);

The output Xml will be similar to this.
C#
<?xml version="1.0" encoding="utf-8"?><List xmlns:ns1="clr-namespace:XmlTest;
assembly=XmlTest" xmlns:exs="https://extendedxmlserializer.github.io/v2" exs:arguments="ns1:XmlData" xmlns="https://extendedxmlserializer.github.io/system">
<Capacity>4</Capacity>
<ns1:XmlData>
<child1>A1</child1>
<child2>A2</child2>
<child3>A3</child3>
</ns1:XmlData>
<ns1:XmlData>
<child1>B1</child1>
<child2>B2</child2>
<child3>B3</child3>
</ns1:XmlData>
<ns1:XmlData>
<child1>C1</child1>
<child2>C2</child2>
<child3>C3</child3>
</ns1:XmlData></List>

Next you want to restructure your xml data so that it's in the same format. The Capacity element can be omitted. If the data file format you have is fixed, you can restructure it by loading it into a StringBuilder and employing the Append and Replace methods to add and replace element names as required.
C#
string xmlContent = File.ReadAllText(@"C:\Temp\orig.xml");
StringBuilder sb = new StringBuilder(xmlContent).
Replace("<Parents>",xmlHeading).Replace("</Parents>","").
Replace("parent","ns1:XmlData").Append("/List>");
IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
string data = sb.ToString();
var MyXmlDataList = serializer.Deserialize<List<XmlData>>(data);

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900