Menu

XML comment in pyxbgen generated schema binding

Help
reet
2017-09-14
2017-09-14
  • reet

    reet - 2017-09-14

    Hi,

    First of all, thanks for pyxb! We use it with great success in our project.

    Now let me describe the problem.

    We generate a binding from a complex schema, fill in the data and write the resulting XML. Works great.

    Now I'd like to add a comment to an arbitrary location in the document. I was not able to find out how to achieve this. If I append a text to an element without creating a schema object first, the text is still inserted as element.

    Any help is appreciated how to achieve this.

    Kind regards

     
  • Peter A. Bigot

    Peter A. Bigot - 2017-09-14

    What do you mean by "comment", and how are you adding it?

    If you have:

    <element>
      <subelt>3</subelt>
      mixed content
    </element>
    

    are you looking to add a real XML comment:

    <element>
      <!-- subelt is optional -->
      <subelt>3</subelt>
      mixed content
    </element>
    

    or more text, or something else?

    If you want to add an XML comment then you'll need to convert the PyXB binding object to DOM and operate on the DOM structure. Use obj.toDOM().

    If you want to add something to the PyXB binding object whatever you add has to be consistent with the schema. If you add text and the model requires an element PyXB may synthesize the element that's required, which sounds like what's happening.

     
  • reet

    reet - 2017-09-14

    Thanks for your answer.

    I want to add an XML comment while constructing the XML via binding python objects, e.g. if an error occurs I want to place the XML comment instead of the element in the non-error case:

    <element>
     <!-- ERROR: out of range
     <subelt>-123123133</subelt>
     -->
     mixed content
    </element>
    

    How can I achieve this with toDOM? I tried:

    el = ... python object from pyxbgen code ..
    bds = pyxb.utils.domutils.BindingDOMSupport()
    dom = el.toDOM(element_name="element")
    bds.appendTextChild('<!-- My comment -->', dom)
    

    I get:

    HierarchyRequestErr: <DOM Text node "u'<!-- My co'..."> cannot be child of <xml.dom.minidom.Document instance at 0x7ff3ec5efa70>

     
  • Peter A. Bigot

    Peter A. Bigot - 2017-09-14

    BindingDOMSupport is special interface used only to affect how PyXB binding objects are converted to or from DOM instances. Once you have the DOM instance you need to use the xml.dom API to manipulate it. You probably need something like:

    dom.root.appendChild(dom.createComment('My comment'));
    
     
  • Peter A. Bigot

    Peter A. Bigot - 2017-09-14

    To be more clear, comments are not part of the PyXB binding data model, so you can't put a comment into a binding object and have it expressed as a comment when the object is converted to XML.

     
  • reet

    reet - 2017-09-14

    Ok, thanks for your help!

     

Log in to post a comment.