Skip to main content
 首页 » 编程设计

c#之如何将对象映射到 C# .NET 中的现有 XML 文件

2024年02月13日1598°冷暖

我有这个现有的 XML 文件作为模板,没有数据,只有简单的节点......这是一个示例:

<?xml version="1.0" encoding="utf-8" ?> 
<catalog> 
  <cd> 
    <title /> 
    <artist /> 
    <country /> 
    <company /> 
    <price /> 
    <year /> 
  </cd> 
</catalog> 

现在我已经为它创建了一个类似的类。

public class Cd 
    { 
        public string Title { get; set; } 
        public string Artist { get; set; } 
        public string Country { get; set; } 
        public string Company { get; set; } 
        public string Price { get; set; } 
        public string Year { get; set; } 
    } 

目的是这样的:

  1. 为 var cd = new Cd(); 对象的属性赋值
  2. 获取现有的 XML 文件(模板),然后传递其中的值(例如将对象映射到现有的 XML)
  3. 将 XML 模板(带有值)转换为 XSLT 以成为 HTML

我想这就是全部。

如何正确地做到这一点? 非常感谢!

请您参考如下方法:

可以使用序列化来实现(1)和(2)

[Serializable] 
    public class Cd 
    { 
 
        public string Title { get; set; } 
 
        public string Artist { get; set; }        
        public string Country { get; set; } 
 
        public string Company { get; set; } 
 
        public string Price { get; set; } 
 
        public string Year { get; set; } 
    } 

现在为了从对象创建 xml 使用:

    public static string SerializeObject<T>(this T obj) 
    { 
        var ms = new MemoryStream(); 
        var xs = new XmlSerializer(obj.GetType()); 
        var xmlTextWriter = new XmlTextWriter(ms, Encoding.UTF8); 
        xs.Serialize(xmlTextWriter, obj); 
        string serializedObject = new UTF8Encoding().GetString((((MemoryStream)xmlTextWriter.BaseStream).ToArray())); 
        return serializedObject; 
 
    } 

为了从 XML 使用创建对象:

public static T DeserializeObject<T>(this string xml) 
    { 
        if (xml == null) 
            throw new ArgumentNullException("xml"); 
        var xs = new XmlSerializer(typeof(T)); 
        var ms = new MemoryStream(new UTF8Encoding().GetBytes(xml)); 
        try 
        { 
            new XmlTextWriter(ms, Encoding.UTF8); 
            return (T)xs.Deserialize(ms); 
        } 
        catch 
        { 
            return default(T); 
        } 
        finally 
        { 
            ms.Close(); 
        } 
    }