Quantcast
Channel: Rhino Developer - McNeel Forum
Viewing all articles
Browse latest Browse all 8546

Python: Parse ghx files with ElementTree?

$
0
0

@chanley wrote:

I am experimenting with parsing ghx files using python. The end goal is to ultimately have something that can loop through all of the ghx files on our server, (first converting all gh files to ghx), and list out used components. NOTE: I am testing this from inside a grasshopper python component, and reading one ghx file, to try and find the correct approach.

I was able to find a post that described some parsing here (Access XML data). But, I was not terribly successful in using that method against a ghx file. With the code below, I am able to get all “items”, (which perhaps is wrong to begin with), but I cant seem to figure out how to only get the items that contain component names. I thought that maybe I could use ElementTree, but I haven’t had much success.

import clr
clr.AddReference("System.Xml")
import System.Xml
import xml.etree.ElementTree as ET

def XMLTest():
    filename = r"C:\CutFillrevised.ghx"
    xmldoc = System.Xml.XmlDocument()
    xmldoc.Load(filename)
    items = xmldoc.GetElementsByTagName('items')

for item in items:
    if item is None: #without this, the first line is the file returns blank, which triggers an error when using the
                     #parse function in ElementTree.
        continue
    itemstr = item.InnerXml.ToString()
    print itemstr


if x == True:
    XMLTest()

I have attached an example ghx file that I have been using to try and read. If anyone has any suggestions, it would be greatly appreciated!

Thanks,
Chris
CutFillrevised.ghx (202.6 KB)
(edited to update GHX file, original file had <?xml version="1.0" encoding="utf-8" standalone="yes"?> removed for testing purposes, new upload is complete file).

Posts: 3

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 8546

Trending Articles