Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Strongly typed object from XML

Tags:

c#

xml

I have a couple of XML files that I need to work with, and I've always used the XElement objects and pulled the data via the attribute name or the XElement's value.

I know there has to be a better way of using XML in C#. What is the best way to either auto generate or manually generate a strong typed object from the XML file?

The xml is in the form of

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

If I could parse an XML file into a List<Group> that would be the best.

The only way I can think to do it is manually create the Group, Rule, and Check objects and manually assign the data. If there is a better, more automated way to do this, please let me know!

like image 333
joe_coolish Avatar asked Mar 03 '11 16:03

joe_coolish


2 Answers

You can use xsd.exe (which installs with the windows SDK, but in various locations depending on version - mine is currently in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin) to generate and xsd from the file, or a cs code file.

For example:

xsd.exe myFile.xml

will get you myFile.xsd in the location of the xml file.

Then,

xsd.exe myFile.xsd /c 

will get you a .cs file with the classes defined. Try xsd.exe /? for full options (you can specify namespaces, etc. as well).

like image 140
Mark Avenius Avatar answered Sep 18 '22 00:09

Mark Avenius


Check out Linq to XSD:

The LINQ to XSD technology provides .NET developers with support for typed XML programming. LINQ to XSD contributes to the LINQ project (.NET Language Integrated Query); in particular, LINQ to XSD enhances the existing LINQ to XML technology.

like image 31
Mikael Östberg Avatar answered Sep 18 '22 00:09

Mikael Östberg