Bera
Bera

Reputation: 1949

Special char in attribute

Is it possible to have special characters in subelement attribute names? I'm trying to use a colon:

category = ET.SubElement(messagedata, 'catid', xmlns="EE.Schema.SSSS.V1R00", xmlsn:comDef="EE.Schema.V1R00")

Which gives me:

SyntaxError: invalid syntax

(I realize now I shouldnt be doing this. I need to understand namespaces...)

Upvotes: 0

Views: 545

Answers (2)

It is not posible without a workaround, nor intended. Identifiers in Python have to follow the following conventions:

  • An identifier must start with a letter or the underscore character
  • An identifier cannot start with a number
  • An identifier can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Identifiers are case-sensitive (age, Age and AGE are three different identifiers)

For more information you can check this site, where I found the points explained.

Upvotes: 0

AKX
AKX

Reputation: 168957

Colons aren't valid parts of identifiers in Python, but you can sidestep this by splatting a dict:

category = ET.SubElement(
    messagedata,
    "catid",
    **{
        "xmlns": "EE.Schema.VSOP.V1R00",
        "xmlsn:comDef": "EE.Schema.V1R00",
    }
)

As an aside, though, if that's supposed to be xmlns:comDef, you should not be managing namespace aliases by hand, but by using the namespace mapping features and spelling out namespaced attributes; "comDef:foo" with that namespace would be {EE.Schema.V1R00}foo and the XML serialization engine would take care of ensuring there are suitable xmlns:... attributes somewhere.

Upvotes: 3

Related Questions