Generate c# object code and assign values to its properties from an xml document

不羁岁月 提交于 2019-12-24 03:06:21

问题


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="'&#xa;'" />

    <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(), '=&quot;', text(), '&quot;;', $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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!