XML reading using Qt

edited January 2018 in Python scripting

I want to read an XML file and convert it to a dict.

The first method works fine in OSX / Linux, but in Windows we are missing a module...

https://stackoverflow.com/questions/2148119/how-to-convert-an-xml-string-to-a-dictionary-in-python

So I tried with Qt. The following doesn't work, and I don't know why.

 filepath = "klayout_Layers_EBeam.lyp"

 #  file=open(filepath,'r')
 #  a=file.read()
 #  file.close()
 qfile = QFile(filepath)
 source=QXmlInputSource(qfile)
 handler=QXmlContentHandler()
 error_handler = QXmlErrorHandler()
 #  source.data = a
 #  reader = QXmlReader()  # error: Abstract method called...
 reader = QXmlSimpleReader()
 reader.setContentHandler(handler)
 reader.setErrorHandler(error_handler)
 reader.parse(source)
 # Error: Ambiguous overload variants - multiple method declarations match arguments in QXmlSimpleReader.parse

thank you
Lukas

Comments

  • edited November -1

    Hi Lukas,

    thanks for reporting this issue. There are actually too many overloads of "parse" - I'll remove one (https://github.com/klayoutmatthias/klayout/issues/62)

    Best regards,

    Matthias

  • edited November -1

    Hi Lukas,

    I have fixed the issue, but I'm afraid it won't be of much help. The simple XML parser API is deployed by implementing a couple of interfaces. That's kind of tedious in Python.

    An easier solution is to use the DOM API. Here is an example how to do basic reading of a .lyp file using the QDom... classes:

    import pya
    
    fileName = "/home/matthias/test.lyp"
    
    # Opens the .lyp file:
    
    doc = pya.QDomDocument("lyp_file")
    file = pya.QFile(fileName)
    if not file.open(pya.QIODevice.ReadOnly):
      raise Exception("Cannot open file '" + fileName + "'")
    
    doc.setContent(file)
    
    # This loop will extract the 'source' and 'name' elements from each 'properties'
    # element on top level:
    
    docElem = doc.documentElement()
    
    n = docElem.firstChild()
    while not n.isNull():
      e = n.toElement()
      if not e.isNull() and e.tagName == "properties":
        source = e.firstChildElement("source")
        name = e.firstChildElement("name")
        print(name.text() + " -> " + source.text())
      n = n.nextSibling()
    

    Best regards,

    Matthias

Sign In or Register to comment.