0

我正在将 xml 数据从 xml 文件获取到 c# 对象,如下所示:

xml:

<OrderItem>
          <OrderItemCode>1234</OrderItemCode>
          <ASIN>dfsdfcs</ASIN>
          <SKU>5MJ1L3</SKU>
          <ItemStatus>Unshipped</ItemStatus>
          <ProductName>xcv/ProductName>
          <Quantity>1</Quantity>
          <ItemPrice>
             <Component>
                        <Type>Principal</Type>
                        <Amount currency="CAD">7.99</Amount>
             </Component>
          </ItemPrice>
</OrderItem>

c#型号:

[XmlRootAttribute("OrderItem")]
public class OrderItem
    {
        [XmlElement("OrderItemCode")]
        public string OrderItemCode { get; set; }

        [XmlElement("ASIN")]
        public string Asin { get; set; }

        [XmlElement("SKU")]
        public string Sku { get; set; }

        [XmlElement("ItemStatus")]
        public string ItemStatus { get; set; }

        [XmlElement("ProductName")]
        public string ProductName { get; set; }

        [XmlElement("Quantity")]
        public long Quantity { get; set; }

        [XmlElement("ItemPrice")]
        public ItemPrice Item_Price { get; set; }

        [XmlElement("PriceDesignation")]
        public string PriceDesignation { get; set; }

        [XmlElement("Promotion")]
        public Promotion Promotion { get; set; }

    }

    public partial class ItemPrice
    {
        [XmlElementAttribute("Component")]
        public List<Component> Component { get; set; }
    }

    public partial class Component
    {
        [XmlElement("Type")]
        public string Type { get; set; }

        [XmlElement("Amount")]
        public Amount Amount { get; set; }
    }

    public partial class Amount
    {
        [XmlAttribute("currency")]
        public string Currencies { get; set; }

        [XmlAttribute("#text")]
        public string Price { get; set; }
    }

反序列化:

 XmlSerializer serializer = new XmlSerializer(typeof(OrderItem));
 TextReader reader = new StreamReader(reportPath);
 OrderItem ordersListXML = (OrderItem)serializer.Deserialize(reader);

在这里,我想<Amount currency="CAD">7.99</Amount>通过反序列化为 c# 对象来获取的值,并且我能够将 Element 的属性“货币”的值获取<Amount currency="CAD">7.99</Amount>到“货币”属性,但无法将元素的文本“7.99”获取<Amount currency="CAD">7.99</Amount>到“价格”属性反序列化后在我的 c# 对象中。

任何人都可以帮助我获得价值!

4

1 回答 1

1

XmlTextAttribute ( ) 允许将条目的值反序列化为字段[XmlText]所以

<Amount currency="CAD">7.99</Amount>

可以反序列化到类

public class Amount
{
    [XmlAttribute("currency")]
    public string Currencies { get; set; }

    [XmlText]
    public string Price { get; set; }
}
于 2020-12-04T19:14:14.043 回答