I have a xml file which has subelements:-
.......
.......
<EnabledFeatureListForUsers>
<FeatureEntitlementDetail>
<UserName>xyz#xyz.com</UserName>
<FeatureList>
<FeatureDetail>
<FeatureId>X</FeatureId>
</FeatureDetail>
</FeatureList>
</FeatureEntitlementDetail>
</EnabledFeatureListForUsers>
.....
.....
I want to add a new sub element FeatureEntitlementDetail with all its subelements/children like username, Feature List, Feature Detail, Feature Id. I tried using SubElement function, but it only adds FeatureEntitlementDetail />. The code which I used was :-
import xml.etree.ElementTree as ET
filename = "XYZ.xml"
xmlTree = ET.parse(filename)
root = xmlTree.getroot()
for element in root.iter('EnabledFeatureListForUsers'):
ET.SubElement(element,"FeatureEntitlementDetail")
Any help is appreciated.
See below
import xml.etree.ElementTree as ET
xml = """
<EnabledFeatureListForUsers>
<FeatureEntitlementDetail>
<UserName>xyz#xyz.com</UserName>
<FeatureList>
<FeatureDetail>
<FeatureId>X</FeatureId>
</FeatureDetail>
</FeatureList>
</FeatureEntitlementDetail>
</EnabledFeatureListForUsers>
"""
root = ET.fromstring(xml)
fed = ET.SubElement(root,'FeatureEntitlementDetail')
un = ET.SubElement(fed,'UserName')
un.text = 'abc.zz.net'
fl = ET.SubElement(fed,'FeatureList')
df = ET.SubElement(fl,'FeatureDetail')
fi = ET.SubElement(df,'FeatureId')
fi.text = 'Z'
ET.dump(root)
output
<?xml version="1.0" encoding="UTF-8"?>
<EnabledFeatureListForUsers>
<FeatureEntitlementDetail>
<UserName>xyz#xyz.com</UserName>
<FeatureList>
<FeatureDetail>
<FeatureId>X</FeatureId>
</FeatureDetail>
</FeatureList>
</FeatureEntitlementDetail>
<FeatureEntitlementDetail>
<UserName>abc.zz.net</UserName>
<FeatureList>
<FeatureDetail>
<FeatureId>Z</FeatureId>
</FeatureDetail>
</FeatureList>
</FeatureEntitlementDetail>
</EnabledFeatureListForUsers>
Related
I'm trying to create a python script that will create a schema to then fill data based on an existing reference.
This is what I need to create:
<srp:root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
this is what I have:
from xml.etree.ElementTree import *
from xml.dom import minidom
def prettify(elem):
rough_string = tostring(elem, "utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
ns = { "SOAP-ENV": "http://www.w3.org/2003/05/soap-envelope",
"SOAP-ENC": "http://www.w3.org/2003/05/soap-encoding",
"xsi": "http://www.w3.org/2001/XMLSchema-instance",
"srp": "http://www.-redacted-standards.org/Schemas/MSRP.xsd"}
def gen():
root = Element(QName(ns["xsi"],'root'))
print(prettify(root))
gen()
which gives me:
<xsi:root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
how do I fix it so that the front matches?
The exact result that you ask for is incomplete, but with a few edits to the gen() function, it is possible to generate well-formed output.
The root element should be bound to the http://www.-redacted-standards.org/Schemas/MSRP.xsd namespace (srp prefix). In order to generate the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" declaration, the namespace must be used in the XML document.
def gen():
root = Element(QName(ns["srp"], 'root'))
root.set(QName(ns["xsi"], "schemaLocation"), "whatever") # Add xsi:schemaLocation attribute
register_namespace("srp", ns["srp"]) # Needed to get 'srp' instead of 'ns0'
print(prettify(root))
Result (linebreaks added for readability):
<?xml version="1.0" ?>
<srp:root xmlns:srp="http://www.-redacted-standards.org/Schemas/MSRP.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="whatever"/>
I am trying to read from a list and add the values as new nodes into an XML in Python
list = ['163','164','165']
and after appending list values into the node trackingnumbers,
The xml should looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
<user>TAIL</user>
<password>20</password>
<trackingnumbers>
<trackingnumber>163</trackingnumber>
<trackingnumber>164</trackingnumber>
<trackingnumber>165</trackingnumber>
</trackingnumbers>
</trackingrequest>
I have got it this far but i am stuck at creating dynamic variables inside a loop, which creates new nodes inside trackingnumbers
def GenerateXML():
root = ET.Element("trackingrequest")
m1 = ET.Element("user")
root.append(m1)
m1.text = 'TAIL'
m2 = ET.Element("password")
root.append(m2)
m2.text = '20'
m3 = ET.Element("trackingnumbers")
root.append(m3)
d = {}
for i in range(list):
d["trackingid_{0}".format(i)] = ET.SubElement(m3, "trackingnumber")
d['trackingid_1'].text = i*2
tree = ET.ElementTree(root)
The idea is to find trackingnumbers and add the required sub elements
import xml.etree.ElementTree as ET
lst = ['163', '164', '165']
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
<user>TAIL</user>
<password>20</password>
<trackingnumbers>
</trackingnumbers>
</trackingrequest>'''
root = ET.fromstring(xml)
tracking_numbers = root.find('.//trackingnumbers')
for num in lst:
tn = ET.SubElement(tracking_numbers, 'trackingnumber')
tn.text = num
ET.dump(root)
output
<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
<user>TAIL</user>
<password>20</password>
<trackingnumbers>
<trackingnumber>163</trackingnumber>
<trackingnumber>164</trackingnumber>
<trackingnumber>165</trackingnumber>
</trackingnumbers>
</trackingrequest>
Hi I am very new to python programming. I have an xml file of structure:
<?xml version="1.0" encoding="UTF-8"?>
-<LidcReadMessage xsi:schemaLocation="http://www.nih.gov http://troll.rad.med.umich.edu/lidc/LidcReadMessage.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.nih.gov" uid="1.3.6.1.4.1.14519.5.2.1.6279.6001.1307390687803.0">
-<ResponseHeader>
<Version>1.8.1</Version>
<MessageId>-421198203</MessageId>
<DateRequest>2007-11-01</DateRequest>
<TimeRequest>12:30:44</TimeRequest>
<RequestingSite>removed</RequestingSite>
<ServicingSite>removed</ServicingSite>
<TaskDescription>Second unblinded read</TaskDescription>
<CtImageFile>removed</CtImageFile>
<SeriesInstanceUid>1.3.6.1.4.1.14519.5.2.1.6279.6001.179049373636438705059720603192</SeriesInstanceUid>
<DateService>2008-08-18</DateService>
<TimeService>02:05:51</TimeService>
<ResponseDescription>1 - Reading complete</ResponseDescription>
<StudyInstanceUID>1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246975630178</StudyInstanceUID>
</ResponseHeader>
-<readingSession>
<annotationVersion>3.12</annotationVersion>
<servicingRadiologistID>540461523</servicingRadiologistID>
-<unblindedReadNodule>
<noduleID>Nodule 001</noduleID>
-<characteristics>
<subtlety>5</subtlety>
<internalStructure>1</internalStructure>
<calcification>6</calcification>
<sphericity>3</sphericity>
<margin>3</margin>
<lobulation>3</lobulation>
<spiculation>4</spiculation>
<texture>5</texture>
<malignancy>5</malignancy>
</characteristics>
-<roi>
<imageZposition>-125.000000 </imageZposition>
<imageSOP_UID>1.3.6.1.4.1.14519.5.2.1.6279.6001.110383487652933113465768208719</imageSOP_UID>
......
There are four which contains multiple . Each contains an . I need to extract the information in from all of these headers.
Right now I am doing this:
import xml.etree.ElementTree as ET
tree = ET.parse('069.xml')
root = tree.getroot()
#lst = []
for readingsession in root.iter('readingSession'):
for roi in readingsession.findall('roi'):
id = roi.findtext('imageSOP_UID')
print(id)
but it ouputs like this:
Process finished with exit code 0.
If anyone can help.
The real problem as been wit the namespace. I tried with and without it, but it didn't work with this code.
ds = pydicom.dcmread("000071.dcm")
uid = ds.SOPInstanceUID
tree = ET.parse("069.xml")
root = tree.getroot()
for child in root:
print(child.tag)
if child.tag == '{http://www.nih.gov}readingSession':
read = child.find('{http://www.nih.gov}unblindedReadNodule')
if read != None:
nodule_id = read.find('{http://www.nih.gov}noduleID').text
xml_uid = read.find('{http://www.nih.gov}roi').find('{http://www.nih.gov}imageSOP_UID').text
if xml_uid == uid:
print(xml_uid, "=", uid)
roi= read.find('{http://www.nih.gov}roi')
print(roi)
This work completely fine to get a uid from dicom image of LIDC/IDRI dataset and then extract the same uid from xml file for it region of interest.
I need to generate xml which looks like this:
<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org">
<typeRef xmlns:ns2="xyz">text</typeRef>
</definitions>
My code looks as follows:
class XMLNamespaces:
ex = 'http://www.example1.org'
xmlns = 'http://www.example2.org'
root = Element('definitions', xmlns='http://www.example2.org', nsmap = {'ex':XMLNamespaces.ex})
type_ref = SubElement(root, 'typeRef')
type_ref.attrib[QName(XMLNamespaces.xmlns, 'ns2')] = 'xyz'
type_ref.text = 'text'
tree = ElementTree(root)
tree.write('filename.xml', pretty_print=True)
The result looks like:
<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org">
<typeRef xmlns:ns0="http://www.example2.org" ns0:ns2="xyz">text</typeRef>
</definitions>
So here is my question:
How to make attribute look like xmlns:ns2="xyz" instead of xmlns:ns0="http://www.example2.org" ns0:ns2="xyz"?
Simply run same process as your opening element where you defined the namespace dictionary with nsmap argument. Notice the added variable in your class object:
from lxml.etree import *
class XMLNamespaces:
ex = 'http://www.example1.org'
xmlns = 'http://www.example2.org'
xyz = 'xyz'
root = Element('definitions', xmlns='http://www.example2.org', nsmap={'ex':XMLNamespaces.ex})
type_ref = SubElement(root, 'typeRef', nsmap={'ns2':XMLNamespaces.xyz})
type_ref.text = 'text'
tree = ElementTree(root)
tree.write('filename.xml', pretty_print=True)
# <definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org">
# <typeRef xmlns:ns2="xyz">text</typeRef>
# </definitions>
My xml :-
<users>
</users>
i need to just append a child element :-
<users>
<user name="blabla" age="blabla" ><group>blabla</group>
</users>
My code giving some error :(
import xml.etree.ElementTree as ET
doc = ET.parse("users.xml")
root_node = doc.find("users")
child = ET.SubElement(root_node, "user")
child.set("username","srquery")
group = ET.SubElement(child,"group")
group.text = "fresher"
tree = ET.ElementTree(root_node)
tree.write("users.xml")
I missed out "append" , but i don't have idea where to add that. Thanks in advance.
Change this line
root_node = doc.find("users")
...to this line
root_node = doc.getroot()
The key takeaway here is that doc is already a reference to the root node, and is accessed with getroot(). doc.find('users') will not return anything, since users is not a child of the root, it's the root itself.
A slightlly modified version to explain what happens:
root = ET.fromstring('<users></users>') # same as your doc=ET.parse(...).find(...), btw. doc=root
el = ET.Element('group') # creating a new element/xml-node
root.append(el) # and adding it to the root
ET.tostring(root)
>>> '<users><group /></users>'
el.text = "fresher" # adding your text
ET.tostring(root)
>>> '<users><group>fresher</group></users>'