【问题标题】:How to deserialize an XML with attributes in C# [duplicate]如何在 C# 中反序列化具有属性的 XML [重复]
【发布时间】:2020-05-30 01:21:48
【问题描述】:

我有一个类似下面的 XML 文件:

<data label="product data">
    <price min="10" max="60">35</price>
</data>

我在 .Net Core 中使用 System.Xml.Serialization。我正在尝试反序列化 XML。对于像这样的常规 XML:

<data>
   <price>35</price>
</data>

以下方法:

public T DeserializeXml<T>(string input)
{
    var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using var stringReader = new StringReader(input);
    var xmlReader = new XmlTextReader(stringReader);
    return (T) xmlSerializer.Deserialize(xmlReader);
}

工作正常并将其解析为特定的类对象。但是当 XML 包含属性时,它不能正常工作,并且在尝试将其反序列化为它的对象时它会崩溃。

这是我的课:

[XmlType("data")]
public class ProductInfo
{
    [XmlElement(ElementName = "price")]
    public string Price{ get; set; }
}

那么我怎样才能检索一个带有属性的有效 XML 以及如何存储它的属性值呢?不确定如何使用 System.Xml.Serialization 库。

【问题讨论】:

标签: c# xml xml-parsing xmlserializer


【解决方案1】:

通过查看 XML,模型应该是这样的

[XmlRoot(ElementName="price")]
public class Price {
    [XmlAttribute(AttributeName="min")]
    public string Min { get; set; }
    [XmlAttribute(AttributeName="max")]
    public string Max { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="price")]
    public Price Price { get; set; }
    [XmlAttribute(AttributeName="label")]
    public string Label { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2016-06-23
    • 2013-04-28
    相关资源
    最近更新 更多