问题
We have a xml file generated from a schema and these are shared with us, we need to generate c# code for from the xml file and set its properties. I can create a parser to do this, but was checking if there are any OOB solutions.
for example
<Customer>
<fname>tom</fname>
<lname>jerry</lname>
</Customer>
to
Customer cust=new Customer();
fname="tom";
lname="jerry";
回答1:
I'd recommend to use Xslt to create your desired code output.
This generic stylesheet will use the root node name as your class and assign every child node with it's content:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no" />
<xsl:variable name="newline" select="'
'" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="/node()[1]">
<xsl:variable name="classname" select="local-name()" />
<xsl:value-of select="concat($classname, ' cust=new ', $classname, '();', $newline)"/>
<xsl:for-each select="./*">
<xsl:value-of select="concat(local-name(), '="', text(), '";', $newline)"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
when applied to
<?xml version="1.0" encoding="utf-8" ?>
<Customer>
<fname>tom</fname>
<lname>jerry</lname>
</Customer>
will produce the following output
Customer cust=new Customer();
fname="tom";
lname="jerry";
来源:https://stackoverflow.com/questions/10562315/generate-c-sharp-object-code-and-assign-values-to-its-properties-from-an-xml-doc