0

我有以下 XML 格式:-

<?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>

XML 值包含 xml 根中的数量。我可以知道如何序列化 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();
        }
    }
4

1 回答 1

2

您可以使用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);
        }
    }
}
于 2017-03-07T10:51:36.090 回答