如何在没有序列化工具的情况下将对象转换为 XML

本文关键字:情况下 对象 转换 XML 工具 序列化 | 更新日期: 2023-09-27 17:57:04

我需要将此类转换为XML文件,但由于某些原因,我无法使用.NET序列化库。有什么方法可以在没有此工具的情况下转换此类?

public class Product
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Desc { get; set; }
    public float Price { get; set; }
    public Category Category { get; set; }
}

我知道XmlSerializer并且已经尝试过并得到结果,但我需要在没有XmlSerializer的情况下执行此操作:

Product product = new Product();
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(product.GetType());
serializer.Serialize(stringwriter, product);
return stringwriter.ToString();

如何在没有序列化工具的情况下将对象转换为 XML

你只需要使用StringBuilder并连接字符串:

StringBuilder builder = new StringBuilder();

然后:

builder.AppendFormat("<instance property='"{0}'" />", instance.Property);

如果您需要支持循环引用场景,其中:产品 => 类别 => 产品,则需要使用可以为每个实例创建唯一运行时标识的机制,因此您不会多次序列化同一对象(检查 ObjectIDGenerator)。

希望对您有所帮助!

您可以根据需要尝试抽象类,例如。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product();
            var x = p.ToXml();
            Console.WriteLine(x.ToString());
            Console.ReadLine();
        }
    }
    public abstract class XmlSerializable
    {
        public XElement ToXml() {
            XElement elm = new XElement(this.GetType().Name);
            this.GetType().GetProperties().ToList().ForEach(p => elm.Add(new XElement(p.Name, p.GetValue(this))));
            return elm;
        }
    }
    public class Product :XmlSerializable
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Desc { get; set; }
        public float Price { get; set; }
    }
}

尝试这样的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication2
{
    class Program
    {
         static void Main(string[] args)
         {
             Product product = new Product()
             {
                 id = 123,
                 title = "A Long Way Home",
                 desc = "Welcome",
                 price = 456.78F,
                 category = new Category() { name = "John" }
             };
             XElement xProduct = new XElement("Product", new object[] {
                 new XElement("Id", product.id),
                 new XElement("Title", product.title),
                 new XElement("Description", product.desc),
                 new XElement("Price", product.price),
                 new XElement("Category", product.category)
             });
        }
    }
    public class Product
    {
        public int id { get; set; }
        public string title { get; set; }
        public string desc { get; set; }
        public float price { get; set; }
        public Category category { get; set; }
    }
    public class Category
    {
        public string name { get; set; }
    }
 }
相关文章: