【问题标题】:deserializing XML to object, wrong values将 XML 反序列化为对象,错误的值
【发布时间】:2016-05-31 13:09:31
【问题描述】:

我已经创建了这样的类:

  [XmlRoot(ElementName = "Control", Namespace = "http://schemas.microsoft.com/VisualStudio/2011/storyboarding/stencilDocument"),Serializable]
    public class ControlStencilXML
    {
        [XmlAttribute("ReferenceName")]
        public string ReferenceName;
        [XmlAttribute("DisplayName")]
        public string DisplayName;
        [XmlAttribute("Revision")]
        public int Revision;
        [XmlAttribute("IsBackground")]
        public bool IsBackground;
        [XmlAttribute("DefaultInsertionPoint")]
        public string DefaultInsertionPoint;
        [XmlAttribute("IsAnimated")]
        public bool IsAnimated;
        [XmlAttribute("KeyWords")]
        public string KeyWords;
        [XmlAttribute("ToolTip")]
        public string ToolTip;
        [XmlElement("ShapeLayouts")]
        public List<ShapeLayout> ShapeLayouts;
    }

[XmlRoot(ElementName = "ShapeLayout", Namespace = "http://schemas.microsoft.com/VisualStudio/2011/storyboarding/stencilDocument")]
public class ShapeLayout
{
    [XmlAttribute("Name")]
    string Name;
    [XmlAttribute("HorizontalAlignment")]
    string HorizontalAlignment;
    [XmlAttribute("VerticalAlignment")]
    string VerticalAlignment;
}

我要反序列化的 XLM:

<?xml version="1.0" encoding="utf-8"?>
<Control ReferenceName="System.Storyboarding.Common.CheckBoxChecked" DisplayName="Checkbox (checked)" ToolTip="Checked checkbox with a text label" Revision="1" IsBackground="false" DefaultInsertionPoint="Default" Keywords="Toggle, Phone" IsAnimated="false" xmlns="http://schemas.microsoft.com/VisualStudio/2011/storyboarding/stencilDocument">
  <ShapeLayouts>
    <ShapeLayout Name="Check" HorizontalAlignment="Left" VerticalAlignment="Center" />
    <ShapeLayout Name="CheckBox" HorizontalAlignment="Left" VerticalAlignment="Center" />
    <ShapeLayout Name="Content" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
  </ShapeLayouts>
</Control>

我尝试反序列化时没有错误,问题是我只获得了第一个 ShapeLayout 对象,并且它的所有值都等于 null。我在哪里犯错了?如何解决?

【问题讨论】:

    标签: c# xml xml-deserialization


    【解决方案1】:

    您还需要一个包装器对象以符合提供的XML -

    [XmlRoot(ElementName = "ShapeLayouts", Namespace = "http://schemas.microsoft.com/VisualStudio/2011/storyboarding/stencilDocument")]
    public class ShapeLayouts
    {
        [XmlElement(ElementName = "ShapeLayout", Namespace = "http://schemas.microsoft.com/VisualStudio/2011/storyboarding/stencilDocument")]
        public List<ShapeLayout> ShapeLayout { get; set; }
    }
    

    【讨论】:

    • 非常感谢,辛苦了。我还将 ShapeLayout 字段的可见性更改为公开。
    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多