简体   繁体   中英

Deserializing child elements as attributes of parent

I have XML files which I need to deserialize. I used the XSD tool from Visual Studio to create c# object files. the generated classes do deserialize the files except not in the way which I need.

I would appreciate any help figuring out how to solve this problem.

The child elements named 'data' should be attributes of the parent element 'task'.

A shortened example of the XML is below:

<task type="Nothing" id="2" taskOnFail="false" >
    <data value="" name="prerequisiteTasks" />
    <data value="" name="exclusionTasks" />
    <data value="" name="allowRepeats" />
    <task type="Wait for Tasks" id="10" taskOnFail="false" >
        <data value="" name="prerequisiteTasks" />
        <data value="" name="exclusionTasks" />
        <data value="" name="allowRepeats" />
    </task>
    <task type="Wait for Tasks" id="10" taskOnFail="false" >
        <data value="" name="prerequisiteTasks" />
        <data value="" name="exclusionTasks" />
        <data value="" name="allowRepeats" />
    </task>
</task>

The Class definition I am trying to deserialize to is in the form:

public class task {
    public string prerequisiteTasks {get;set;}
    public string exclusionTasks {get;set;}
    public string allowRepeats {get;set;}

    [System.Xml.Serialization.XmlElementAttribute("task")]
    public List<task> ChildTasks {get;set;}
}

The child 'task's are fine, but the generated files put the 'data' elements into an array of data[] rather than as named members of the task class as I need.

C# can´t deserialize generic lists. So what you need to do is to define how generic collection data will be deserialized. To acomplish that you got to implement GetObjectData(SerializationInfo info, StreamingContext context).

To help check-out this article. There is a sample code:

http://www.codeproject.com/KB/cs/CSV2SQLScript.aspx

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