Thứ Ba, 16 tháng 7, 2019

XML to C# class và ngược lại

A. XML to C# class

Dùng tool online: https://xmltocsharp.azurewebsites.net/

+ Chuẩn hóa chuỗi XML trước khi dùng tool trên:
Tạo app Winform để add tag đóng vào XML:

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoCloseXMLTag
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAddCloseTag_Click(object sender, EventArgs e)
        {
            txtOutput.Clear();

            var lines = txtInput.Text.Split('\n').ToList();
            List<string> linesChuanHoa = new List<string>();

            //add chuỗi có tag đóng
            foreach (var line in lines)
            {
                string strRegex = @"[\t]+";
                Regex myRegex = new Regex(strRegex, RegexOptions.None);
                string strReplace = @"";


                String temp = line;
                String tempRegex = myRegex.Replace(temp, strReplace).Trim();
                if (tempRegex.Contains("</"))
                    linesChuanHoa.Add(tempRegex);

            }

            foreach (var line in lines)
            {
                // MessageBox.Show(line);

                string strRegex = @"[\t]+";
                Regex myRegex = new Regex(strRegex, RegexOptions.None);
                string strReplace = @"";


                String temp = line;
                String tempRegex = myRegex.Replace(temp, strReplace).Trim();
                //MessageBox.Show("-"+temp+"-");
                if (!tempRegex.Contains(@"</") && !linesChuanHoa.Contains("</" + tempRegex.Replace("<", "")))
                {
                    txtOutput.AppendText(temp + tempRegex.Replace("<", "</") + "\r\n");
                }
                else
                {
                    txtOutput.AppendText(temp + "\r\n");
                }
            }
        }
    }
}

**Lưu ý nhớ test Validate XML: https://www.freeformatter.com/xml-validator-xsd.html

B. C# class to XML:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace XMLtoCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer c = new Customer("a", "b");
            string xml = ToXML(c);
            Console.Write(xml);

            Console.ReadKey();
        }

        public static string ToXML<T>(T obj)
        {
            using (var stringwriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stringwriter, obj);
                return stringwriter.ToString();
            }
        }

        public static Customer LoadFromXMLString(string xmlText)
        {
            using (var stringReader = new System.IO.StringReader(xmlText))
            {
                var serializer = new XmlSerializer(typeof(Customer));
                return serializer.Deserialize(stringReader) as Customer;
            }
        }
    }

    //TOOL ONLINE: xml to C#: https://xmltocsharp.azurewebsites.net/

    [XmlRoot(ElementName = "CustomerKK")]
    public class Customer
    {
        [XmlElement(ElementName = "CustomerIDDD")]
        public string CustomerID { get; set; }

        [XmlElement(ElementName = "ContactName")]
        public string ContactName { get; set; }

        public Customer(String CustomerID, String ContactName)
        {
            this.CustomerID = CustomerID;
            this.ContactName = ContactName;
        }
        public Customer() { }

        public string ToXML()
        {
            using (var stringwriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(this.GetType());
                serializer.Serialize(stringwriter, this);
                return stringwriter.ToString();
            }
        }

        public static Customer LoadFromXMLString(string xmlText)
        {
            using (var stringReader = new System.IO.StringReader(xmlText))
            {
                var serializer = new XmlSerializer(typeof(Customer));
                return serializer.Deserialize(stringReader) as Customer;
            }
        }
    }

}

Không có nhận xét nào:

Đăng nhận xét