我需要将此类转换为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();
答案 0 :(得分:1)
您只需要使用StringBuilder
并连接字符串:
StringBuilder builder = new StringBuilder();
然后:
builder.AppendFormat("<instance property=\"{0}\" />", instance.Property);
如果您需要支持循环参考场景,其中:Product =&gt; Category =&gt;产品,然后您需要使用可以为每个实例创建唯一运行时标识的机制,因此您不会多次序列化同一个对象(请查看ObjectIDGenerator)。
希望它有所帮助!
答案 1 :(得分:0)
您可以根据自己的要求尝试抽象课程,例如
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; }
}
}
答案 2 :(得分:0)
尝试这样的代码
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; }
}
}