Write 'xsi:' in front of attribute with lxml for python 3Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?How to know if an object has an attribute in PythonDoes Python have a string 'contains' substring method?

How do you justify more code being written by following clean code practices?

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

How do I tell my boss that I'm quitting in 15 days (a colleague left this week)

Can I cause damage to electrical appliances by unplugging them when they are turned on?

Do I have to take mana from my deck or hand when tapping a dual land?

Why does the Persian emissary display a string of crowned skulls?

What is this high flying aircraft over Pennsylvania?

How to make a list of partial sums using forEach

Overlapping circles covering polygon

Should I warn a new PhD Student?

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

Echo with obfuscation

How to make money from a browser who sees 5 seconds into the future of any web page?

Is there a RAID 0 Equivalent for RAM?

Would a primitive species be able to learn English from reading books alone?

Check if object is null and return null

Showing mass murder in a kid's book

How do I fix the group tension caused by my character stealing and possibly killing without provocation?

Why didn’t Eve recognize the little cockroach as a living organism?

Sigmoid with a slope but no asymptotes?

Limit max CPU usage SQL SERVER with WSRM

How to test the sharpness of a knife?

Identifying "long and narrow" polygons in with PostGIS

In One Punch Man, is King actually weak?



Write 'xsi:' in front of attribute with lxml for python 3


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?How to know if an object has an attribute in PythonDoes Python have a string 'contains' substring method?













0















I'm adding elements to an xml file.



The document's root is as follows



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">


And elements to add look like



<Element xsi:type="some type">
<Sub1>Some text</Sub1>
<Sub2>More text</Sub2>
...
</Element>


I'm trying to find a way for lxml to write 'xsi:' in front of my Element's attibute. This xml file is used by a program to which's source code I do not have access to. I read in a few other questions how to do it by declaring the nsmap of the xml's root, and then again in the child's attribute, which I tried but it didn't work. So far I have (that's what didn't work, the ouput file did not contain the xsi prefix):



element = SubElement(_parent=parent, 
_tag='some tag',
attrib='%stype' % XSI: 'some type'
nsmap='xsi': XSI) # Where XSI = namespace address


The namespace is declared properly in the xml file I parse, so I don't know why this isn't working.
The output I get is the element as shown above without the 'xsi:' prefix and all on one line:



<Element type="some type"><Sub1>Some text</Sub1><Sub2>More text</Sub2>...</Element>


If anyone can also point out why in this line



self.tree.write(self.filename, pretty_print=True, encoding='utf-8')


the 'pretty_print' option doesn't work (all printed out in one line), it would be greatly appreciated.



Here is a code example of my script:



from math import floor
from lxml import etree
from lxml.etree import SubElement


def Element(root, sub1: str):
if not isinstance(sub1, str):
raise TypeError
else:
element = SubElement(root, 'Element')
element_sub1 = SubElement(element, 'Sub1')
element_sub1.text = sub1
# ...
# Omitted additional SubElements
# ...
return element


def Sub(root, sub5_sub: str):
XSI = "http://www.w3.org/2001/XMLSchema-instance"
if not isinstance(sub5_sub, str):
raise TypeError
else:
sub = SubElement(root, 'Sub5_Sub', '%stype' % XSI: 'SomeType', nsmap='xsi': XSI)
# ...
# Omitted additional SubElements
# ...
return sub


class Generator:
def __init__(self) -> None:
self.filename = None
self.csv_filename = None
self.csv_content = []
self.tree = None
self.root = None
self.panel = None
self.panels = None

def mainloop(self) -> None:
"""App's mainloop"""
while True:
# Getting files from user
xml_filename = input('Enter path to xml file : ')

# Parsing files
csv_content = ['field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub2', 'field2': 'something'] # Replaces csv file that I use
tree = etree.parse(xml_filename)
root = tree.getroot()

elements = root.find('Elements')

for element in elements:
if element.find('Sub1').text in ['ElementSub1', 'ElementSub2']:
for line in csv_content:
if element.find('Sub5') is not None:
Sub(root=element.find('Sub5'),
sub5_sub=line['field2'])

tree.write(xml_filename, pretty_print=True, encoding='utf-8')

if input('Continue? (Y) Quit (n)').upper().startswith('Y'):
elements.clear()
continue
else:
break

@staticmethod
def get_x(x: int) -> str:
if not isinstance(x, int):
x = int(x)
return str(int(floor(9999 / 9 * x)))

@staticmethod
def get_y(y: int) -> str:
if not isinstance(y, int):
y = int(y)
return str(int(floor(999 / 9 * y)))

def quit(self) -> None:
quit()


if __name__ == "__main__":
app = Generator()
app.mainloop()
app.quit()


Here is what it outputs:



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Elements>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
</Element>
</Elements>
</Root>


For some reason, this piece of code does what I want but my real code doesn't. I've come to realize that it does put a prefix on some sub elements with the type attribute, but not all and on those it puts the prefix, it isn't always just 'xsi:'. I found a quick and dirty way to fix this problem which is less than ideal (find and replace through the file for xsi-type -> accepted by lxml's api to xsi:type). What still isn't working though is that it's all printed out in one line despite the pretty_print parameter being true.










share|improve this question
























  • "but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

    – mzjn
    Nov 20 '17 at 20:06












  • It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

    – mzjn
    Nov 20 '17 at 20:47











  • @mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

    – Narkael
    Nov 21 '17 at 13:49











  • It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

    – mzjn
    Nov 21 '17 at 16:25
















0















I'm adding elements to an xml file.



The document's root is as follows



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">


And elements to add look like



<Element xsi:type="some type">
<Sub1>Some text</Sub1>
<Sub2>More text</Sub2>
...
</Element>


I'm trying to find a way for lxml to write 'xsi:' in front of my Element's attibute. This xml file is used by a program to which's source code I do not have access to. I read in a few other questions how to do it by declaring the nsmap of the xml's root, and then again in the child's attribute, which I tried but it didn't work. So far I have (that's what didn't work, the ouput file did not contain the xsi prefix):



element = SubElement(_parent=parent, 
_tag='some tag',
attrib='%stype' % XSI: 'some type'
nsmap='xsi': XSI) # Where XSI = namespace address


The namespace is declared properly in the xml file I parse, so I don't know why this isn't working.
The output I get is the element as shown above without the 'xsi:' prefix and all on one line:



<Element type="some type"><Sub1>Some text</Sub1><Sub2>More text</Sub2>...</Element>


If anyone can also point out why in this line



self.tree.write(self.filename, pretty_print=True, encoding='utf-8')


the 'pretty_print' option doesn't work (all printed out in one line), it would be greatly appreciated.



Here is a code example of my script:



from math import floor
from lxml import etree
from lxml.etree import SubElement


def Element(root, sub1: str):
if not isinstance(sub1, str):
raise TypeError
else:
element = SubElement(root, 'Element')
element_sub1 = SubElement(element, 'Sub1')
element_sub1.text = sub1
# ...
# Omitted additional SubElements
# ...
return element


def Sub(root, sub5_sub: str):
XSI = "http://www.w3.org/2001/XMLSchema-instance"
if not isinstance(sub5_sub, str):
raise TypeError
else:
sub = SubElement(root, 'Sub5_Sub', '%stype' % XSI: 'SomeType', nsmap='xsi': XSI)
# ...
# Omitted additional SubElements
# ...
return sub


class Generator:
def __init__(self) -> None:
self.filename = None
self.csv_filename = None
self.csv_content = []
self.tree = None
self.root = None
self.panel = None
self.panels = None

def mainloop(self) -> None:
"""App's mainloop"""
while True:
# Getting files from user
xml_filename = input('Enter path to xml file : ')

# Parsing files
csv_content = ['field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub2', 'field2': 'something'] # Replaces csv file that I use
tree = etree.parse(xml_filename)
root = tree.getroot()

elements = root.find('Elements')

for element in elements:
if element.find('Sub1').text in ['ElementSub1', 'ElementSub2']:
for line in csv_content:
if element.find('Sub5') is not None:
Sub(root=element.find('Sub5'),
sub5_sub=line['field2'])

tree.write(xml_filename, pretty_print=True, encoding='utf-8')

if input('Continue? (Y) Quit (n)').upper().startswith('Y'):
elements.clear()
continue
else:
break

@staticmethod
def get_x(x: int) -> str:
if not isinstance(x, int):
x = int(x)
return str(int(floor(9999 / 9 * x)))

@staticmethod
def get_y(y: int) -> str:
if not isinstance(y, int):
y = int(y)
return str(int(floor(999 / 9 * y)))

def quit(self) -> None:
quit()


if __name__ == "__main__":
app = Generator()
app.mainloop()
app.quit()


Here is what it outputs:



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Elements>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
</Element>
</Elements>
</Root>


For some reason, this piece of code does what I want but my real code doesn't. I've come to realize that it does put a prefix on some sub elements with the type attribute, but not all and on those it puts the prefix, it isn't always just 'xsi:'. I found a quick and dirty way to fix this problem which is less than ideal (find and replace through the file for xsi-type -> accepted by lxml's api to xsi:type). What still isn't working though is that it's all printed out in one line despite the pretty_print parameter being true.










share|improve this question
























  • "but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

    – mzjn
    Nov 20 '17 at 20:06












  • It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

    – mzjn
    Nov 20 '17 at 20:47











  • @mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

    – Narkael
    Nov 21 '17 at 13:49











  • It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

    – mzjn
    Nov 21 '17 at 16:25














0












0








0








I'm adding elements to an xml file.



The document's root is as follows



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">


And elements to add look like



<Element xsi:type="some type">
<Sub1>Some text</Sub1>
<Sub2>More text</Sub2>
...
</Element>


I'm trying to find a way for lxml to write 'xsi:' in front of my Element's attibute. This xml file is used by a program to which's source code I do not have access to. I read in a few other questions how to do it by declaring the nsmap of the xml's root, and then again in the child's attribute, which I tried but it didn't work. So far I have (that's what didn't work, the ouput file did not contain the xsi prefix):



element = SubElement(_parent=parent, 
_tag='some tag',
attrib='%stype' % XSI: 'some type'
nsmap='xsi': XSI) # Where XSI = namespace address


The namespace is declared properly in the xml file I parse, so I don't know why this isn't working.
The output I get is the element as shown above without the 'xsi:' prefix and all on one line:



<Element type="some type"><Sub1>Some text</Sub1><Sub2>More text</Sub2>...</Element>


If anyone can also point out why in this line



self.tree.write(self.filename, pretty_print=True, encoding='utf-8')


the 'pretty_print' option doesn't work (all printed out in one line), it would be greatly appreciated.



Here is a code example of my script:



from math import floor
from lxml import etree
from lxml.etree import SubElement


def Element(root, sub1: str):
if not isinstance(sub1, str):
raise TypeError
else:
element = SubElement(root, 'Element')
element_sub1 = SubElement(element, 'Sub1')
element_sub1.text = sub1
# ...
# Omitted additional SubElements
# ...
return element


def Sub(root, sub5_sub: str):
XSI = "http://www.w3.org/2001/XMLSchema-instance"
if not isinstance(sub5_sub, str):
raise TypeError
else:
sub = SubElement(root, 'Sub5_Sub', '%stype' % XSI: 'SomeType', nsmap='xsi': XSI)
# ...
# Omitted additional SubElements
# ...
return sub


class Generator:
def __init__(self) -> None:
self.filename = None
self.csv_filename = None
self.csv_content = []
self.tree = None
self.root = None
self.panel = None
self.panels = None

def mainloop(self) -> None:
"""App's mainloop"""
while True:
# Getting files from user
xml_filename = input('Enter path to xml file : ')

# Parsing files
csv_content = ['field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub2', 'field2': 'something'] # Replaces csv file that I use
tree = etree.parse(xml_filename)
root = tree.getroot()

elements = root.find('Elements')

for element in elements:
if element.find('Sub1').text in ['ElementSub1', 'ElementSub2']:
for line in csv_content:
if element.find('Sub5') is not None:
Sub(root=element.find('Sub5'),
sub5_sub=line['field2'])

tree.write(xml_filename, pretty_print=True, encoding='utf-8')

if input('Continue? (Y) Quit (n)').upper().startswith('Y'):
elements.clear()
continue
else:
break

@staticmethod
def get_x(x: int) -> str:
if not isinstance(x, int):
x = int(x)
return str(int(floor(9999 / 9 * x)))

@staticmethod
def get_y(y: int) -> str:
if not isinstance(y, int):
y = int(y)
return str(int(floor(999 / 9 * y)))

def quit(self) -> None:
quit()


if __name__ == "__main__":
app = Generator()
app.mainloop()
app.quit()


Here is what it outputs:



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Elements>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
</Element>
</Elements>
</Root>


For some reason, this piece of code does what I want but my real code doesn't. I've come to realize that it does put a prefix on some sub elements with the type attribute, but not all and on those it puts the prefix, it isn't always just 'xsi:'. I found a quick and dirty way to fix this problem which is less than ideal (find and replace through the file for xsi-type -> accepted by lxml's api to xsi:type). What still isn't working though is that it's all printed out in one line despite the pretty_print parameter being true.










share|improve this question
















I'm adding elements to an xml file.



The document's root is as follows



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">


And elements to add look like



<Element xsi:type="some type">
<Sub1>Some text</Sub1>
<Sub2>More text</Sub2>
...
</Element>


I'm trying to find a way for lxml to write 'xsi:' in front of my Element's attibute. This xml file is used by a program to which's source code I do not have access to. I read in a few other questions how to do it by declaring the nsmap of the xml's root, and then again in the child's attribute, which I tried but it didn't work. So far I have (that's what didn't work, the ouput file did not contain the xsi prefix):



element = SubElement(_parent=parent, 
_tag='some tag',
attrib='%stype' % XSI: 'some type'
nsmap='xsi': XSI) # Where XSI = namespace address


The namespace is declared properly in the xml file I parse, so I don't know why this isn't working.
The output I get is the element as shown above without the 'xsi:' prefix and all on one line:



<Element type="some type"><Sub1>Some text</Sub1><Sub2>More text</Sub2>...</Element>


If anyone can also point out why in this line



self.tree.write(self.filename, pretty_print=True, encoding='utf-8')


the 'pretty_print' option doesn't work (all printed out in one line), it would be greatly appreciated.



Here is a code example of my script:



from math import floor
from lxml import etree
from lxml.etree import SubElement


def Element(root, sub1: str):
if not isinstance(sub1, str):
raise TypeError
else:
element = SubElement(root, 'Element')
element_sub1 = SubElement(element, 'Sub1')
element_sub1.text = sub1
# ...
# Omitted additional SubElements
# ...
return element


def Sub(root, sub5_sub: str):
XSI = "http://www.w3.org/2001/XMLSchema-instance"
if not isinstance(sub5_sub, str):
raise TypeError
else:
sub = SubElement(root, 'Sub5_Sub', '%stype' % XSI: 'SomeType', nsmap='xsi': XSI)
# ...
# Omitted additional SubElements
# ...
return sub


class Generator:
def __init__(self) -> None:
self.filename = None
self.csv_filename = None
self.csv_content = []
self.tree = None
self.root = None
self.panel = None
self.panels = None

def mainloop(self) -> None:
"""App's mainloop"""
while True:
# Getting files from user
xml_filename = input('Enter path to xml file : ')

# Parsing files
csv_content = ['field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub1', 'field2': 'something',
'field1': 'ElementSub2', 'field2': 'something'] # Replaces csv file that I use
tree = etree.parse(xml_filename)
root = tree.getroot()

elements = root.find('Elements')

for element in elements:
if element.find('Sub1').text in ['ElementSub1', 'ElementSub2']:
for line in csv_content:
if element.find('Sub5') is not None:
Sub(root=element.find('Sub5'),
sub5_sub=line['field2'])

tree.write(xml_filename, pretty_print=True, encoding='utf-8')

if input('Continue? (Y) Quit (n)').upper().startswith('Y'):
elements.clear()
continue
else:
break

@staticmethod
def get_x(x: int) -> str:
if not isinstance(x, int):
x = int(x)
return str(int(floor(9999 / 9 * x)))

@staticmethod
def get_y(y: int) -> str:
if not isinstance(y, int):
y = int(y)
return str(int(floor(999 / 9 * y)))

def quit(self) -> None:
quit()


if __name__ == "__main__":
app = Generator()
app.mainloop()
app.quit()


Here is what it outputs:



<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Elements>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
<Sub5>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/>
<Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/><Sub5_Sub xsi:type="SomeType"/></Sub5>
</Element>
<Element>
<Sub1>ElementSub1</Sub1>
</Element>
</Elements>
</Root>


For some reason, this piece of code does what I want but my real code doesn't. I've come to realize that it does put a prefix on some sub elements with the type attribute, but not all and on those it puts the prefix, it isn't always just 'xsi:'. I found a quick and dirty way to fix this problem which is less than ideal (find and replace through the file for xsi-type -> accepted by lxml's api to xsi:type). What still isn't working though is that it's all printed out in one line despite the pretty_print parameter being true.







python xml python-3.x lxml






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '17 at 13:47







Narkael

















asked Nov 20 '17 at 19:40









NarkaelNarkael

138




138












  • "but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

    – mzjn
    Nov 20 '17 at 20:06












  • It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

    – mzjn
    Nov 20 '17 at 20:47











  • @mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

    – Narkael
    Nov 21 '17 at 13:49











  • It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

    – mzjn
    Nov 21 '17 at 16:25


















  • "but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

    – mzjn
    Nov 20 '17 at 20:06












  • It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

    – mzjn
    Nov 20 '17 at 20:47











  • @mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

    – Narkael
    Nov 21 '17 at 13:49











  • It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

    – mzjn
    Nov 21 '17 at 16:25

















"but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

– mzjn
Nov 20 '17 at 20:06






"but it didn't work". What didn't work? Please show us complete but minimal code (Minimal, Complete, and Verifiable example).

– mzjn
Nov 20 '17 at 20:06














It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

– mzjn
Nov 20 '17 at 20:47





It's better now, but you haven't provided code that we can copy-paste and just run. Pieces are missing (import statements, the bit where you parse the original file, etc.). Exactly what output do you get? Sorry to be a nag, but we should not have to guess.

– mzjn
Nov 20 '17 at 20:47













@mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

– Narkael
Nov 21 '17 at 13:49





@mzjn Don't be sorry, I'm still learning about best practices on SO and I can't expect help without giving a little information.

– Narkael
Nov 21 '17 at 13:49













It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

– mzjn
Nov 21 '17 at 16:25






It is great that you posted more complete code, but please note that I asked for a Minimal program. Surely it must be possible to create a much smaller program that reproduces the problem. But you also wrote "For some reason, this piece of code does what I want but my real code doesn't", so now I don't know how we can help at all.

– mzjn
Nov 21 '17 at 16:25













1 Answer
1






active

oldest

votes


















1














I just recently encountered this scenario and was able to successfully create an attribute with the xsi:



qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")
element = etree.Element('Element', {qname: "some type")

root.append(element)


this outputs something like



<Element xsi:type="some type">





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47399807%2fwrite-xsi-in-front-of-attribute-with-lxml-for-python-3%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I just recently encountered this scenario and was able to successfully create an attribute with the xsi:



    qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")
    element = etree.Element('Element', {qname: "some type")

    root.append(element)


    this outputs something like



    <Element xsi:type="some type">





    share|improve this answer



























      1














      I just recently encountered this scenario and was able to successfully create an attribute with the xsi:



      qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")
      element = etree.Element('Element', {qname: "some type")

      root.append(element)


      this outputs something like



      <Element xsi:type="some type">





      share|improve this answer

























        1












        1








        1







        I just recently encountered this scenario and was able to successfully create an attribute with the xsi:



        qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")
        element = etree.Element('Element', {qname: "some type")

        root.append(element)


        this outputs something like



        <Element xsi:type="some type">





        share|improve this answer













        I just recently encountered this scenario and was able to successfully create an attribute with the xsi:



        qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")
        element = etree.Element('Element', {qname: "some type")

        root.append(element)


        this outputs something like



        <Element xsi:type="some type">






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 2:45









        catzillacatzilla

        1,056924




        1,056924





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47399807%2fwrite-xsi-in-front-of-attribute-with-lxml-for-python-3%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved