基于属性名称反序列化 xml 作为我在 C# 中的类的属性 [英] Deserialize xml base on attribute name as properties of my class in C#

查看:28
本文介绍了基于属性名称反序列化 xml 作为我在 C# 中的类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下描述的 xml 文件

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>

我想把这个xml文件映射到这个类:

I want to mapping this xml file to this class:

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

    public string Field2
    {
        get;set;
    }
}

我的问题是如何将属性名称映射到Row"类的属性?顺便说一下,我能够基于标签(字段)映射到行"类的属性.我的观点是如何映射带有字段标记上属性名称值的额外条件?

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?

对不起我的英语.

提前致谢.

推荐答案

没有内置的 xml 序列化程序(特别是 XmlSerializerDataContractSerializer)允许您使用 <要映射到成员的属性的 em>value.属性的 name - 当然(例如 <cust id="12345" name="Fred"/>) - 但不是您的 <字段名称="Field2">....

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>.

因此,您必须使用XmlDocumentXDocumentXmlReader 之类的工具手动执行此操作.或者,也许通过 xslt 运行它以将其转换为 XmlSerializer 可以 处理的内容,即您可以构造(通过 xslt):

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, i.e. 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)

这篇关于基于属性名称反序列化 xml 作为我在 C# 中的类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆