Design A strongly typed object from XML

I have several XML files that I need to work with, and I always used XElement objects and pulled data through the attribute name or XElement value.

I know there must be a better way to use XML in C #. What is the best way to either generate or manually create a strong typed object from an XML file?

xml is in the form

<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 the XML file into a List<Group> , which would be the best.

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

+6
c # xml
source share
5 answers

You can use xsd.exe (which is installed using the Windows SDK, but in different places depending on the version - mine is currently located in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin ) for generating and xsd from a cs file or code file.

For instance:

 xsd.exe myFile.xml 

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

Then

 xsd.exe myFile.xsd /c 

will provide you with a .cs file with specific classes. Try xsd.exe /? for complete parameters (you can also specify namespaces, etc.).

+8
source share

Check out Linq to XSD :

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

+4
source share

If you have an XML schema, you can create classes using tools like xsd.exe (Windows SDK), svcutil.exe (WCF), or (my personal preference) an open source alternative ( Xsd2Code ).

+1
source share

You can put annotations in your class and then use the XmlSerializer to serialize / deserialize class instances to / from XML - if you need a more personal approach, and your class also implements IXmlSerializable , then puts that serialization / deserialization code in the class.

+1
source share

If you can change the XML format to suit your needs, one of the ways I know is using WSDL .

+1
source share

All Articles