繁体   English   中英

嵌套属性和XML反序列化

[英]Nested attributes and XML deserialization

我实际上停留在当前的项目中。

我有以下结构的XML:

<ExampleCol>
  <ElementWithAttribute attr="null">ElementWithAttribute</ElementWithAttribute>
  <AnotherCol> 
    <Row attr="row1">Name = 1 </Row>
    <Row attr="row2"> Name = 2 </Row>
  </AnotherCol>
<ExampleCol>

我无法更改该XML结构。

目前,我正在与这些课程合作:

[XmlRoot]
public class ExampleCol
{
    [XmlElement("ElementWithAttribute")]
    public ElementWithAttribute ewa1 {get;set}

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

public class ElementWithAttribute 
{
  [XmlElement("ElementWithAttribute")
  public string Value {get;set;}

  [XmlAttribute("attr")
  public string attr {get;set;}
}

public class AnotherCol
{
  [XmlArray]
  [XmlArrayItem("Row")
  public Row[] RowCollection {get;set;}
}

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

  [XmlAttribute("attr")]
  public string Attribute [get;set;]
}

显然,这无法反序列化AnotherColElementWithAttribute

(显然,因为RowElementWithAttribute每个类都希望一个新元素作为子元素。

但是我实在太傻了,看不到实现目标需要做些什么。

有人可以给我一些提示吗?

提前致谢。

这是您能够反序列化这组XML所需的代码:

[XmlRoot(ElementName="ExampleCol")]
public class Test
{
    [XmlElement("ElementWithAttribute")]
    public ElementWithAttribute Element = new ElementWithAttribute();

    [XmlArray(ElementName="AnotherCol")]
    public List<Row> AnotherCol = new List<Row>();
    public Test()
    {

    }
}

public class ElementWithAttribute
{
    public ElementWithAttribute()
    {

    }
    [XmlAttribute]
    public string attr { get; set; }
    [XmlText]
    public string value { get; set; }
}

public class Row
{
    public Row()
    {

    }
    [XmlAttribute]
    public string attr { get; set; }
    [XmlText]
    public string value { get; set; }
}

您需要使用[XmlText]

[XmlRoot]
public class ExampleCol
{

    [XmlText] // Here !!
    public ElementWithAttribute ewa1 {get;set}

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


}

这将有助于读取元素的文本内容作为属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM