Xmlserializer - 控制元素-属性配对(修订版) [英] Xmlserializer - Control Element-Attribute Pairing (revised)

查看:24
本文介绍了Xmlserializer - 控制元素-属性配对(修订版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XmlSerializer 做我想做的一切,只有一个例外.我需要将一个元素与另一个元素配对作为该元素的属性.我不想编写一个完全自定义的序列化方法.这是我的课程:

The XmlSerializer does everything I want with one exception. I need to pair an element with another element as an attribute of that element. I don't want to write a completely custom serialize method. Here's my class:

public class Transaction
{
   [XmlElement("ID")]
   public int m_id;

   [XmlElement("TransactionType")]
   public string m_transactiontype;

   [XmlAttribute("TransactionTypeCode")]
   public string m_transactiontypecode;
}

我实例化和序列化如下;

I instantiate and serialize as follows;

   Transaction tx = new Transaction();

   tx.m_id = 1;   
   tx.m_transactiontype = "Withdrawal";  
   tx.m_transactiontypecode = "520";

   StringWriter o = new
   StringWriter(CultureInfo.InvariantCulture);
   XmlSerializer s = new
   XmlSerializer(typeof(Transaction));   
   s.Serialize(o, tx);   
   Console.Write(o.ToString());

给我:

   <Transaction TransactionTypeCode="520">
     <ID>1</ID>
     <TransactionType>Withdrawal</TransactionType> 
   </Transaction>

我想要:

   <Transaction>
     <ID>1</ID>
     <TransactionType TransactionTypeCode="520">Withdrawal</TransactionType>
   </Transaction>

有人 (Chris Dogget) 建议:

Someone (Chris Dogget) suggested:

   public class Transaction
   {

       [XmlElement("ID")]
       public int m_id;

       public TransactionType m_transactiontype;
   }

   public class TransactionType
   {
       public TransactionType(){}
       public TransactionType(string type) { this.m_transactiontype = type; }

       [XmlTextAttribute]
       public string m_transactiontype;

       [XmlAttribute("TransactionTypeCode")]
       public string m_transactiontypecode; 
   }

TransactionType 类的使用看起来很有希望 - 您能告诉我如何在序列化之前实例化这些类吗?

The use of the TransactionType class looks promising - can you show me how you would instantiate the classes before serializing?

谢谢!

推荐答案

public class Transaction
{

    [XmlElement("ID")]
    public int m_id;

    public TransactionType type;
}

public class TransactionType
{
    public TransactionType(){}
    public TransactionType(string type) { this.@Type = type; }

    [XmlTextAttribute]
    public string @Type;

    [XmlAttribute("TypeCode")]
    public string typecode; 
}

给我这个:

<?xml version="1.0" encoding="utf-16"?>
<Transaction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ID>1</ID>
    <type TypeCode="520">Withdrawal</type>
</Transaction>

不幸的是,Type"是 .NET 中的实际类型,因此您不能真正使用它(至少大写)作为您的字段名称.

Unfortunately, "Type" is an actual type in .NET, so you can't really use that (uppercase at least) as your field name.

这篇关于Xmlserializer - 控制元素-属性配对(修订版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆