设计来自XML的强类型对象

joe*_*ish 6 c# xml

我有几个需要使用的XML文件,我总是使用XElement对象并通过属性名称或XElement的值来提取数据.

我知道在C#中使用XML必须有更好的方法.从XML文件自动生成或手动生成强类型对象的最佳方法是什么?

xml的形式是

<Group id="####">
    <title>Some Title</title>
    <description>some description</description>
    <Rule id="ID_##" severity="medium" weight="10.0">
        <version>1.001</version>
        <title>Another Title</title>
        <description>Very long description</description>
        <fixtext fixref="F-31r1_fix">Description of fix</fixtext>
        <fix id="F-31r1_fix"/>
        <check system="C-7883r4_chk">
            <check-content-ref name="M" href="URI"/>
            <check-content>Content</check-content>
        </check>
    </Rule>
</Group>
Run Code Online (Sandbox Code Playgroud)

如果我可以将XML文件解析成List<Group>最好的文件.

我能想到的唯一方法是手动创建Group,Rule和Check对象并手动分配数据.如果有更好,更自动化的方法,请告诉我!

Mar*_*ius 8

你可以使用xsd.exe(它与windows SDK一起安装,但在不同的位置,具体取决于版本 - 我目前正在使用C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin)从文件生成xsd或cs代码文件.

例如:

xsd.exe myFile.xml
Run Code Online (Sandbox Code Playgroud)

将在xml文件的位置获取myFile.xsd.

然后,

xsd.exe myFile.xsd /c 
Run Code Online (Sandbox Code Playgroud)

将为您提供.cs定义类的文件.尝试xsd.exe /?完整选项(您也可以指定名称空间等).