【问题标题】:c# parse xml array with attributec# 使用属性解析xml数组
【发布时间】:2014-11-11 11:18:40
【问题描述】:

我正在尝试解析一个 xml 数组,它在一个奇怪的地方有一个属性。

这是我的(在 stackowerflow 上的某处找到)解析器代码:

public static string Serialize (object objectToSerialize)
{
    MemoryStream mem = new MemoryStream ();          
    XmlSerializer ser = new XmlSerializer (objectToSerialize.GetType ());         
    ser.Serialize (mem, objectToSerialize);     
    UTF8Encoding utf = new UTF8Encoding ();
    return utf.GetString (mem.ToArray ());
}

public static T Deserialize<T> (string xmlString)
{
    byte[] bytes = Encoding.UTF8.GetBytes (xmlString);
    MemoryStream mem = new MemoryStream (bytes);         
    XmlSerializer ser = new XmlSerializer (typeof(T));
    return (T)ser.Deserialize (mem);
}

这适用于所有情况(我需要),除了这里:

<hr>
    <type n="easy">
        <scores>
            <country name="USA">
                <score nickname="steve" rank="1">1982</score>
                <score nickname="bill" rank="2">1978</score>
...

这是我的模板类:

public class CountryList
{
    public CountryList ()
    {
    }

    [XmlArray("country")]
    [XmlArrayItem("score")]
    public ScoreAndRank[]
        country;

    [XmlAttribute("name")]
    public string
        name;
    }
}

分数数组已正确解析,但“名称”始终为空。 我什至可以得到 n 的值(如 [XmlAttribute("n")])。 任何提示如何解决这个问题?

编辑:基于 Svein Fidjestøl 链接的解决方案

[XmlType("country")]
public class ScoreContainer
{
    public ScoreContainer ()
    {
    }
    [XmlElement("score")]
    public ScoreAndRank[] country;

    [XmlAttribute("name")]
    public string name;

}

像魅力一样工作。

【问题讨论】:

    标签: c# xml xml-parsing


    【解决方案1】:

    为了给 XML 数组添加 XML 属性,需要为数组元素声明一个类。

    更详细的答案可以在这里找到:How do I add a attribute to a XmlArray element (XML Serialization)?

    【讨论】:

    • 谢谢,现在可以使用了。我已经为问题添加了解决方案。
    猜你喜欢
    • 2021-09-16
    • 2012-12-10
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多