Note that there are some explanatory texts on larger screens.

plurals
  1. POXmlserializer - Control Element-Attribute Pairing (revised)
    primarykey
    data
    text
    <p>The <code>XmlSerializer</code> 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:</p> <pre><code>public class Transaction { [XmlElement("ID")] public int m_id; [XmlElement("TransactionType")] public string m_transactiontype; [XmlAttribute("TransactionTypeCode")] public string m_transactiontypecode; } </code></pre> <p>I instantiate and serialize as follows;</p> <pre><code> 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()); </code></pre> <p>Gives me:</p> <pre><code> &lt;Transaction TransactionTypeCode="520"&gt; &lt;ID&gt;1&lt;/ID&gt; &lt;TransactionType&gt;Withdrawal&lt;/TransactionType&gt; &lt;/Transaction&gt; </code></pre> <p>I want:</p> <pre><code> &lt;Transaction&gt; &lt;ID&gt;1&lt;/ID&gt; &lt;TransactionType TransactionTypeCode="520"&gt;Withdrawal&lt;/TransactionType&gt; &lt;/Transaction&gt; </code></pre> <p>Someone (Chris Dogget) suggested:</p> <pre><code> 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; } </code></pre> <p>The use of the TransactionType class looks promising - can you show me how you would instantiate the classes before serializing?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload