开发者

Automatically generating code from a text or xml file and then compiling?

I would like to know how I could generate code from a text file in a particular format into a VB.net or C# source file. For instance: I would like my code generating program to read text file having the following format:

<category1>
      <subcategory>
        entry1
        entry2
      </subcategory>
</Category1>

And then generate code in vb.net(or C#):

Dim TreeNode1 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("entry1") 
Dim TreeNode2 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("entry2") 
Dim TreeNode3 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("subcategory", New System.Windows.Forms.TreeNode() {TreeNode1, TreeNode2})

The idea is to compile the main code after the user have modified the txt file and used the code gener开发者_开发技巧ating program. I would prefer to write the code generating program in C, python or C#. How can I go about this?


I'm not really convinced this is a python question, despite the tags and penultimate sentence in the question, but here's a python answer.

>>> from xml.etree import ElementTree as etree
>>> corpus = '''<category1>
...       <subcategory>
...         entry1
...         entry2
...       </subcategory>
... </category1>
... '''
>>> doc = etree.fromstring(corpus)
>>> for subcategory in doc.getchildren():
...     for entry in filter(bool,
...                         map(str.strip,
...                             subcategory.text.split('\n'))):
...         print "entry output: (%s)" % entry
...     print "subcategory output (%s)" % subcategory.tag
... 
entry output: (entry1)
entry output: (entry2)
subcategory output (subcategory)
>>> 


You need to write parser to parse your text file. Once parser generate string which is similar to VB.net or C# code, you can use Emit to compile to a temporary assembly


Use the CSharpCodeProvider, set up a string skeleton that is the rest of you class, parse your file, and then inject your generated code in the correct location.

Info about the CSharpCodeProvider

Note that you will want to build in memory and set build executable to false. Here is an example on how to do that, it also shows how set the assemblies for the compiler to the assemblies of the currently executing file.

I know this is a bit vague but how you set up the actual CSharpCodeProvider depends on what you are trying to do. Also beware that if you get FileNotFound exceptions you are getting compile errors, the top link gives a nice solution on how to throw them in a readable fashion.


This depends on which of mentioned languages is most familiar to you. I'd recommend to go with python, because you can start playing with it right away from command line interpreter.

There is standard library for xml parsing:

from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name

Then you iterate through elements, either by name, like this:

for node in dom1.getElementsByTagName('category1'):
    ...

or straight-forward for all elements:

for node in dom1.childNodes:
   ...

Below is the command line interpreter transcript of how to inspect the object tree (>>> stand for interpreter prompt):

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dom = parseString ('<root>contents</root>')
>>> dom.childNodes
[<DOM Element: root at 0x7f0d4519f680>]
>>> dom.childNodes[0]
<DOM Element: root at 0x7f0d4519f680>
>>> dom.childNodes[0].childNodes
[<DOM Text node "u'contents'">]
>>> dom.childNodes[0].childNodes[0]
<DOM Text node "u'contents'">
>>> dom.childNodes[0].childNodes[0].nodeValue
u'contents'
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜