构建用于反序列化xml的c#类的麻烦(c# xml) XmlSerializer

本文关键字:xml XmlSerializer 麻烦 用于 构建 反序列化 | 更新日期: 2023-09-27 18:12:58

我试图用XmlSerializer (c#)反序列化XML,看起来像:

    <strokes>
      <stroke timestamp="1405376883559">
        <coord x="58.425" y="43.2375" d="0.0"/>
        <coord x="58.6125" y="42.825" d="13.0"/>
        <coord x="58.7625" y="42.7125" d="26.0"/>
        <coord x="58.875" y="42.7125" d="40.0"/>
      </stroke>
      <stroke timestamp="1405376884991">
        <coord x="67.95" y="40.6125" d="0.0"/>
        <coord x="68.025" y="40.5" d="13.0"/>
        <coord x="68.0625" y="40.3875" d="26.0"/>
      </stroke>
      <stroke timestamp="1405376885557">
        <coord x="70.425" y="41.85" d="0.0"/>
        <coord x="70.35" y="42.0" d="13.0"/>
        <coord x="70.35" y="42.075" d="26.0"/>
        <coord x="70.4625" y="42.1125" d="40.0"/>
        <coord x="70.6125" y="42.15" d="53.0"/>
      </stroke>
      <stroke timestamp="1405376886058">
        <coord x="70.6875" y="44.175" d="0.0"/>
        <coord x="70.575" y="44.25" d="13.0"/>
      </stroke>
      <stroke timestamp="1405376886689">
        <coord x="78.375" y="42.7125" d="0.0"/>
        <coord x="78.1125" y="42.9" d="13.0"/>
        <coord x="77.8125" y="43.0875" d="26.0"/>
        <coord x="77.475" y="43.2375" d="40.0"/>
      </stroke>
      </stroke>
    </strokes>

和我的错误类看起来像这样

    [XmlRoot("strokes", IsNullable = false)]
    public class Strokes
    {
        private List<Stroke> strokes;
    }
    public class Stroke
    {
        public string timestamp;
        [XmlArrayAttribute("stroke")]
        List<coord> stroke;
    }
    [Serializable]
    public class coord
    {
        [XmlAttribute]
        public string x;
        [XmlAttribute]
        public string y;
        [XmlAttribute]
        public string d;
    }

我想我缺少一些类属性来描述笔画对象有一个数组和时间戳。我得到一个"未知节点",甚至触发了xml节点"stroke"

我如何构造我的c#对象来适应这个xml?

构建用于反序列化xml的c#类的麻烦(c# xml) XmlSerializer

这应该能奏效:

[XmlRoot("strokes", IsNullable = false)]
public class Strokes
{
    [XmlElement("stroke")]
    public List<Stroke> strokes;
}
public class Stroke
{
    [XmlAttribute]
    public string timestamp;
    [XmlElement("coord")]
    public List<coord> coords;
}
[Serializable]
public class coord
{
    [XmlAttribute]
    public string x;
    [XmlAttribute]
    public string y;
    [XmlAttribute]
    public string d;
}

关键是让你想要(反)序列化public的所有内容,并在coord s列表中使用XmlElement而不是XmlArrayAttribute

在Mikael Svenson对类似问题的回答中有一个非常有用的提示:

我是这样做的:获取xml,从中生成一个模式(xsd)Visual Studio。然后在模式上运行xsd.exe生成一个类。(和一些小的编辑)

如果您对发布的XML执行此操作,您将获得以下coord元素列表的工作版本,例如:

[System.Xml.Serialization.XmlElementAttribute("coord")]
public strokesStrokeCoord[] coord {
    get {
        return this.coordField;
    }
    set {
        this.coordField = value;
    }
}