简体   繁体   中英

Nested attributes and XML deserialization

I am actually stuck in my current project.

I've got a XML of the following structure:

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

I am not able to change that XML structure.

Currently I am working with those classes:

[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;]
}

Obviously it cannot deserialize AnotherCol and ElementWithAttribute .

(Obviously, because each class of Row and ElementWithAttribute expects a new element as a child.

But I'm just too dumb to see what changes I need to do to achieve my goals.

Anyone could provide me some hints?

Thanks in advance.

Here is the code you'll require to be able to deserialize that set of 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; }
}

You need to use [XmlText] :

[XmlRoot]
public class ExampleCol
{

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

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


}

This will help to read the text content of the element as a property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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