简体   繁体   中英

Serialize XML without tag name

I have the following XML format:-

<?xml version="1.0"?>        
<Price xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <amount>
    <currency>USD</currency>
    100
  </amount>
  <amount>
    <currency>EUR</currency>
    50
  </amount>
</Price>

the XML value contains the amount in the xml root. May I know how can I serialize the value of 100 & 50 ?

    [Serializable]
    [XmlRoot("amount")]
    public sealed class amount
    {
        [XmlElement("currency")]
        public string currency{ get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<amount> {new amount() {Description = "USD"}, new amount() {Description = "EUR"}};
            var serializer = new XmlSerializer(typeof(List<amount>), new XmlRootAttribute("Price"));
            var ms = new MemoryStream();
            serializer.Serialize(ms, list);
            ms.Position = 0;
            var result = new StreamReader(ms).ReadToEnd();
        }
    }

You can use XmlText :

[XmlRoot("amount")]
public sealed class amount
{
    [XmlElement("currency")]
    public string Description { get; set; }

    // http://stackoverflow.com/a/1528429/613130
    [XmlIgnore]
    public int Value { get; set; }

    [XmlText]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public string ValueXml
    {
        get
        {
            return XmlConvert.ToString(Value);
        }
        set
        {
            Value = XmlConvert.ToInt32(value);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM