Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Example:
C#
public class MYELEMENT
{
    public string value;
}

The above would produce something like the following:
<MYELEMENT><value>string</value></MYELEMENT>

For my purposes I need the following:
<MYELEMENT>string</MYELEMENT>

I am creating an array of elements that preserves the order of the original elements serialized from an external source.
C#
public class MYROOT
{
    [XmlElement(typeof(MYELEMENT1))]
    [XmlElement(typeof(MYELEMENT2))]
    [XmlElement(typeof(MYELEMENT3))]
    public object[] nodes { get; set; }
}

There may be one or more elements of each type that can appear any order. Therefore, each element is represented as a class object.

The code, as written, works fine except that Deserializing this
<MYELEMENT>1</MYELEMENT>

produces the following when Serializing it out
<MYELEMENT />

Which is correct at the moment, because there is no sub-element.

Is there an XML attribute or other method that can be applied to produce what I need?

Something like this
C#
public class MYELEMENT
{
    [this is the elements value]
    public string value;
}

or this
C#
[this is a wrapper for the real element]
public class Foo
{
    public string MYELEMENT { get; set; }
}


Thanks!
Posted

The solution is to use [XmlText()] for correct results.

Example:
C#
public class MYELEMENT1
{
    [XmlText()]
    public string value;
}

public class MYELEMENT2
{
    [XmlText(typeof(int))]
    public int value;
}


Result of Serializing :
XML
<MYELEMENT1>string</MYELEMENT1>
<MYELEMENT2>1</MYELEMENT2>
 
Share this answer
 
I would recommend to avoid "manual" serialization on this level and use Data Contracts.

This approach is most non-intrusive, easiest to implement and most flexible at the same time.

Please see: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

Please also see my past answers where I advocate this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deseralize a json string array[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900