3

I need to add a prefix to my attribute in my xml elements like:

<Database xmlns:xsi="http://www.w3.org/" xmlns="http://www.staubli.com/">
    <Data name="pPointTraj" access="public" xsi:type="array" type="PointTraj" size="2">
        <Field name="pPoint" xsi:type="array" type="pointRx" size="1">

I am talking about the xmlns: and xsi: elements here.

So ideally I want to do that:

Database = ET.Element("Database", xmlns:xsi="http://www.w3.org/")
Datas = ET.SubElement(Database, "Datas")
Data = ET.SubElement(Datas, "Data", name="pPointTraj", access="public", xsi:type="array", type="PointTraj", size="2")

From what I've tried I can put it without the term behind the : but if I put the prefix I get a syntax error.

I am stuck here and couldn't find my answer on the internet, can someone help me on this? thank you in advance.


EDIT : QName

@mzjn shared this answer to another question so I tried it but I still have things that I want to get rid of and I don't know how.

from xml.etree import ElementTree as ET

NS1 = "http://www.w3.org/" 

ET.register_namespace("xsi", NS1) 

qname1 = ET.QName(NS1, "D")    # Element QName 

root = ET.Element("Database", {qname1:""},xmlns="http://www.staubli.com/") 
print(ET.tostring(root).decode())

The code above gives me

<Database xmlns:xsi="http://www.w3.org/" xsi:D="" xmlns="http://www.staubli.com/" />

And I want to get rid of the xsi:D="". Do you know how I can achieve this? Thank you.

Jack
  • 695
  • 10
  • 29
  • 1
    You should be able to use `QName` to add a namespaced attribute. See https://stackoverflow.com/a/58678592/407651 and https://stackoverflow.com/a/31074030/407651. – mzjn Jun 26 '20 at 14:57
  • @mzjn this solution works but I have a problem... I get an unwanted part of thr namespace ``I would like to get rid of `xsi:D=""` I have updated my question so all the elements are there. Can you help me a bit more? – Jack Jun 29 '20 at 08:00
  • What is the exact wanted output? That is not clear. – mzjn Jun 29 '20 at 08:53
  • @mzjn sorry I updated my original question. The wanted output is `` – Jack Jun 29 '20 at 08:55
  • In the question you also mention `Data`, `Datas`, and `Field` elements. It is still not clear what the complete wanted output is. Please edit the question. Do not add this information in a comment. – mzjn Jun 29 '20 at 09:01
  • @mzjn I have updated my original question. The wanted output is at the beginning. – Jack Jun 29 '20 at 09:03
  • @mzjn the EDIT part is just a bit of testing to see if I could get the wanted result for the first line of the wanted output showed at the beginning of my original question, I'm sorry if I was confusing – Jack Jun 29 '20 at 09:11

0 Answers0