简体   繁体   中英

Deserialize xml base on attribute name as properties of my class in C#

I have xml file like i describe below

<Root name="myRoot">
    <Field name = "myField">"blabla</Field>
    <List name="data">
        <Row name="data">
            <Field name="Field1">sample</Field>
            <Field name="Field2">sample</Field>
        </Row>     
    </List>
</Root>

I want to mapping this xml file to this class:

public class Row
{
    public string Field1
    {
        get;set;
    }

    public string Field2
    {
        get;set;
    }
}

my problem is how to mapping atrribute name to properties of "Row" class ? by the way i able to mapping to properties of "Row" class based on tag (Field). my point is how to mapping with extra condition which is with value of attribute name on field tag?

sorry for my english.

Thanks in advance.

No inbuilt xml serializer (in particular, neither XmlSerializer nor DataContractSerializer ) allows you to use the value of an attribute to map to a member. The name of an attribute - sure (for example <cust id="12345" name="Fred"/> ) - but not your <Field name="Field2">...</Field> .

Consequently, you will have to do this manually using something like XmlDocument , XDocument or XmlReader . Alternatively, perhaps run it through xslt to turn it into something that XmlSerializer can handle, ie you could construct (via xslt):

<myRoot>
    <myField>"blabla</myField>
    <data>
        <data>
            <Field1>sample</Field1>
            <Field2>sample</Field2>
        </data>
    </data>
</myRoot>

(which would involve use of <xsl:element name="@name"> in particular)

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