嵌套属性和XML反序列化

时间:2012-02-28 11:23:44

标签: c# xml

我实际上被困在我目前的项目中。

我有一个以下结构的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类都需要一个新元素作为孩子。

但是我太傻了,看不出我为实现目标需要做些什么改变。

任何人都可以提供一些提示吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

以下是您需要能够反序列化该组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; }
}

答案 1 :(得分:0)

您需要使用[XmlText]

[XmlRoot]
public class ExampleCol
{

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

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


}

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