Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

Parsing element which contains a string value (simpleContent) and at least one attribute (using pyxbgen and xsd)

Help
2014-01-13
2014-01-14
  • Petros Makris
    Petros Makris
    2014-01-13

    Hello all,

    I need to define the following in an XML document

    <cmd bg='true' shell='false'>command_to_be_executed</cmd>
    

    I managed to create the following XSD type

    <xsd:complexType name="CommandElement">
        <xsd:simpleContent>
        <xsd:extension base="xsd:string">
            <xsd:attribute name="bg" type="xsd:boolean" default="false" />
            <xsd:attribute name="shell" type="xsd:boolean" default="true" />
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>
    

    Let's say I get and object with reference name 'cmd1' by parsing the line

    <cmd bg='true' shell='false'>command_to_be_executed</cmd>
    

    I can access the element attributes but how can I access the string value content (simpleContent) ?

    cmd1.bg == true
    cmd1.shell = false
    cmd1.XXXXXX = command_to_be_executed
    

    Thanks in advance

     
  • Peter A. Bigot
    Peter A. Bigot
    2014-01-13

    Given a complete schema and bindings generated into module xx:

    import xx
    
    i = xx.CreateFromDocument("<cmd bg='true' shell='false'>command_to_be_executed</cmd>")
    
    print i.bg
    print i.shell
    print i.value()
    

    There is some discussion of this in this part of the documentation, though I admit it'd be easier to find if it were in the user reference rather than the architecture reference.

    The obvious next question is "so how do I change the value without affecting the attributes", which currently requires something like this:

    i._resetContent()
    i.append('something')
    print i.toxml('utf-8')
    

    I don't particularly like that, and have opened trac/223 so it can be addressed.

     
  • Peter A. Bigot
    Peter A. Bigot
    2014-01-13

    Note that the ugly workaround is only necessary if you already have an instance and want to change it. To create an instance that's correct from the start is trivial:

    i = xx.cmd('body', bg=True, shell=False)
    print i.toxml('utf-8')
    

    where the full schema I'm using is:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:complexType name="CommandElement">
        <xsd:simpleContent>
        <xsd:extension base="xsd:string">
            <xsd:attribute name="bg" type="xsd:boolean" default="false" />
            <xsd:attribute name="shell" type="xsd:boolean" default="true" />
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>
    <xsd:element name="cmd" type="CommandElement"/>
    </xsd:schema>
    
     
  • Petros Makris
    Petros Makris
    2014-01-14

    Thank you