【问题标题】:Need help on creating a generalized method for generating XML在创建生成 XML 的通用方法方面需要帮助
【发布时间】:2013-09-19 11:55:49
【问题描述】:

我想写一个使用 C# 创建 xml 文件的通用方法。

假设我的 XML 骨架如下所示

<root>
    <customer>
        <mobile></mobile>
        <email></email>
        <external></external>
        <firstname></firstname>
        <lastname></lastname>
        <gender></gender>
        <registered></registered>
        <custom>
            <field>
                <name></name>
                <value></value>
            </field>
            <field>
                <name></name>
                <value></value>
            </field>
        </custom>
    </customer>         
</root>

如果我将传递一个包含所有必需值的对象,我的方法应该返回一个带有值的 xml。

请注意:- 我的 xml 结构将来可以随时更改。

目前我已经为创建不同的 XML 文件创建了单独的方法。因此,每当 xml 发生任何更改时,我都必须对方法进行更改并再次部署。

编辑:

我的客户类别如下所示

class Customer
    {       
        public string CustomerNumber { get; set; }
        public string Title { get; set; }
        public string county { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string companyname { get; set; }
        public string AddressOne { get; set; }
        public string AddressTwo { get; set; }
        public string AddressThree { get; set; }
        public string city { get; set; }
        public string postcode { get; set; }
        public string country { get; set; }
        public string email { get; set; }
        public string RegisteredStore { get; set; }
        public string mailable { get; set; }
        public string rentable { get; set; }
        public string emailable { get; set; }
        public string JoinDate { get; set; }
        public string CustomerExternalID { get; set; }
        public string customergender { get; set; }
        public string dateofbirth { get; set; }
        public string homenumber { get; set; }
        public string Mobile { get; set; }       

        //Custom Fields
        public string CurrencyRef { get; set; }
        public string InvitationStatus { get; set; }
        public string LastMailDate { get; set; }
        public string LastOrderDate { get; set; }
        public string NearestShop { get; set; }
        public string NearestShopDistance { get; set; }
        public string Region { get; set; }       
        public string ShopperType { get; set; }
    }

我正在使用 XElement 为客户创建 xml,但是当在自定义字段中添加任何新字段时,我必须更改代码以获得所需的 xml 输出。

【问题讨论】:

  • 我们不知道您的对象是什么样的,或者属性何时应该以自己的元素名称与您提到的“自定义”字段结束 - 基本上,这个问题缺少太多细节我们现在来实际回答。
  • 到目前为止你有什么?向我们展示您用于生成 xml 的对象
  • 添加了更多信息。

标签: c# xml linq-to-xml


【解决方案1】:

将对象转换为 XML 称为“对象序列化”——获取内存中的对象并将其转换为可写入磁盘或通过网络发送的 XML 的过程。任何对象都可以被序列化(变成 XML 或 JSON)。

下面是一个教程链接,该教程展示了如何在 C# 中执行此操作: http://support.microsoft.com/kb/815813

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多