Refencing the node of a .props file in python - python

Sorry if this is a silly question, but I've been trying to reference the directory in a .props file, that way I could parse it and use it as a variable for a python project. The problem however is that the header of the file is being treated as the root of the program, and I haven't been able to reference the main root no matter what I've done. I've tried 'json.dumps()', 'root.iter()', 'root.findall()', and a slew of other options to try and get past the header, but everytime I try the result either generates an error, or nothing at all.
I'm guessing it's because I'm using a props file and while similar, these solutions are supposed to be for .xml files, but I haven't found anything that implies I should be dealing with .props files any differently.
In short. How can I take the information in the MainRoot node below, and, in a separate python program, parse it and make it into a variable? Said props file is below.
<!--YouFoundMe.props-->
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MainRoot>..\..\..\YouFoundMe</MainRoot>
</PropertyGroup>
</Project>
This may not be important, but if it helps, I'll also post a python file containing some of the failed methods I tried below:
import xml.etree.ElementTree as ET
import json
tree = ET.parse('YouFoundMe\YouFoundMe.props')
root = tree.getroot()
FIND_ME_DIR = json.dumps(root.attrib)
boobop = json.dumps(root.tag)
print(FIND_ME_DIR)
for child in root:
print(child.tag)
print(child.attrib)
for MainRoot in root.iter('Project'):
print(MainRoot.attrib)
for MainRoot in root.iter('PropertyGroup'):
print(MainRoot.attrib)
for MainRoot in root.iter('MainRoot'):
print(MainRoot.attrib)
for child in root.iter('MainRoot'):
print("Aything? Please?")
for PROP in root.findall('PropertyGroup'):
result = PROP.find('MainRoot').text
print(result)
for MainRoot in root.findall('Project'):
print("Text")
for MainRoot in root.findall('PropertyGroup'):
print("Text")
for MainRoot in root.findall('MainRoot'):
print("Text")
element = root.find('Project')
if not element: # careful!
print("element not found, or element has no subelements")
if element is None:
print("element not found")
test = str(root.get("Project"))
print(test)
test = str(root.get("PropertyGroup"))
print(test)
test = str(root.get("MainRoot"))
print(test)
print(tree)
print(root)

Notice that your XML has default namespace declared at the root element level:
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
Note that descendant elements without prefix, including MainRoot, inherit this default namespace implicitly. You can define a prefix that references the above default namespace and then use that prefix to find MainRoot, for example:
ns = { 'd': 'http://schemas.microsoft.com/developer/msbuild/2003' }
main_root = root.find('.//d:MainRoot', namespaces=ns)
print(main_root.text)

Related

I want to update value of a particular xml tag using python code?

My xml file looks like below :-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Messages xmlns="URL/sampleMessages-v1">
<Header>
<TransactionId>0</TransactionId>
<RequestNo>41194812</RequestNo>
<VNo>6789</VNo>
<Source></Source>
</Header>
...
...
</Messages>
I want to read it and change the RequestNo value
<RequestNo>41194812</RequestNo> to
<RequestNo>41194000</RequestNo>
I am using ElementTree module currently. I am using windows machine currently.
I want to update the value in the same file.
Ihave tried below code :-
for elem in root:
for subelem in elem:
#print (subelem.tag)
if 'RequestNo' in subelem.tag :
#print (subelem.text)
subelem.text="41194813"
But i am not able to see the change or i dont know currently how to write this new value subelem.text="41194813" in existing xml file.
Your for loop does the job: it did replace the text correctly. The change is in your root variable. You can verify that by adding the following line right after the for loop:
ElementTree.dump(root)
Now that you have the XML updated, you will need to write that into a file:
tree.write('newfile.xml')
Where tree is the result of ElementTree.parse(). So, to put everything together:
tree = ElementTree.parse('messages.xml')
root = tree.getroot()
for elem in root:
for subelem in elem:
if 'RequestNo' in subelem.tag:
subelem.text = '41194813'
break
tree.write('messages-new.xml')
Dealing with Namespaces
Your XML document contains namespaces, so if you plan to search for a tag, you need to include the namespaces in the tag names. Here is an alternative solution which deals with namespaces:
tree = ElementTree.parse('messages.xml')
root = tree.getroot()
namespaces = {'xxx': 'URL/sampleMessages-v1'}
node = root.find('xxx:Header/xxx:RequestNo', namespaces)
if node is not None:
node.text = '41194813'
tree.write('messages-new.xml')
In the above example, I just gave your namespace the name 'xxx', it can be anything 'foo', 'bar', ... but should be used as prefix in the call to root.find().
Removing "ns0" from Output File
In order to remove "ns0" from output file, you need to register the namespace before writing:
ElementTree.register_namespace('', 'URL/sampleMessages-v1')
tree.write('messages-new.xml')

ElementTree appends extra information when getting root element

I have an xml like shown below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dtbook PUBLIC "-//INFO//INFO info 2005-3//EN" "http://url">
<dtbook xmlns="http://www.daisy.org/z3986/2005/dtbook/" version="2005-3" xml:lang="ml">
<head>....
</dtbook>
I open the file like so,
with open("filename.xml") as f:
tree = ET.parse(f)
root = tree.getroot()
When I try to get the root tag, I get,
print(root.tag)
{http://www.daisy.org/z3986/2005/dtbook/}dtbook
whereas if I remove all the attributes from the root tag i.e. dtbook, I get the correct output i.e. dtbook
print(root.tag)
dtbook
I cannot remove the attributes. Is there a way to get this working without removing the attributes??
This is called a namespace and is supposed to be in front. You can simply remove the namespace by splitting your string at {}

Python xml etree find parent node by text of child

I have an XML that's like this
<xml>
<access>
<user>
<name>user1</name>
<group>testgroup</group>
</user>
<user>
<name>user2</name>
<group>testgroup</group>
</user>
<access>
</xml>
I now want to add a <group>testgroup2</group> to the user1 subtree.
Using the following I can get the name
access = root.find('access')
name = [element for element in access.iter() if element.text == 'user1']
But I can't access the parent using name.find('..') it tells me
AttributeError: 'list' object has no attribute 'find'.
Is there any possibility to access the exact <user> child of <access> where the text in name is "user1"?
Expected result:
<xml>
<access>
<user>
<name>user1</name>
<group>testgroup</group>
<group>testgroup2</group>
</user>
<user>
<name>user2</name>
<group>testgroup</group>
</user>
<access>
</xml>
Important notice: I can NOT use lxml to use getparent() method, I am stuck to xml.etree
To do that, using 'find', you need to do like this: for ele in name:
ele.find('..') # To access ele as an element
Here is how I solved this, if anyone is interested in doing this stuff in xml instead of lxml (why ever).
According to suggestion from
http://effbot.org/zone/element.htm#accessing-parents
import xml.etree.ElementTree as et
tree = et.parse(my_xmlfile)
root = tree.getroot()
access = root.find('access')
# ... snip ...
def iterparent(tree):
for parent in tree.getiterator():
for child in parent:
yield parent, child
# users = list of user-names that need new_group added
# iter through tupel and find the username
# alter xml tree when found
for user in users:
print "processing user: %s" % user
for parent, child in iterparent(access):
if child.tag == "name" and child.text == user:
print "Name found: %s" % user
parent.append(et.fromstring('<group>%s</group>' % new_group))
After this et.dump(tree) shows that tree now contains the correctly altered user-subtree with another group tag added.
Note: I am not really sure why this works, I just expect that yield gives a reference to the tree and therefore altering the parent yield returned alters the original tree. My python knowledge is not good enough to be sure about this tho. I just know that it works for me this way.
You can write a recursive method to iterate through the tree and capture the parents.
def recurse_tree(node):
for child in node.getchildren():
if child.text == 'user1':
yield node
for subchild in recurse_tree(child):
yield subchild
print list(recurse_tree(root))
# [<Element 'user' at 0x18a1470>]
If you're using Python 3.X, you can use the nifty yield from ... syntax rather than iterating over the recursive call.
Note that this could possibly yield the same node more than once (if there are multiple children containing the target text). You can either use a set to remove duplicates, or you can alter the control flow to prevent this from happening.
you can directly use findall() method to get the parent node that match the name='user1'. see below code
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml') #build tree object using your xml
root = tree.getroot() #using tree object get the root
for parent in root.findall(".//*[name='user1']"):
# the predicate [name='user1'] preceded by asterisk will give
# all elements where child having name='user1'
parent.append(ET.fromstring("<group>testgroup2</group>"))
# if you want to see the xml after adding the string
ET.dump(root)
# optionally to save the xml
tree.write('output.xml')

How to deal with xmlns values while parsing an XML file?

I have the following toy example of an XML file. I have thousands of these. I have difficulty parsing this file.
Look at the text in second line. All my original files contain this text. When I delete i:type="Record" xmlns="http://schemas.datacontract.org/Storage" from second line (retaining the remaining text), I am able to get accelx and accely values using the code given below.
How can I parse this file with the original text?
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfRecord xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="Record" xmlns="http://schemas.datacontract.org/Storage">
<AvailableCharts>
<Accelerometer>true</Accelerometer>
<Velocity>false</Velocity>
</AvailableCharts>
<Trics>
<Trick>
<EndOffset>PT2M21.835S</EndOffset>
<Values>
<TrickValue>
<Acceleration>26.505801694441629</Acceleration>
<Rotation>0.023379150593228679</Rotation>
</TrickValue>
</Values>
</Trick>
</Trics>
<Values>
<SensorValue>
<accelx>-3.593643144</accelx>
<accely>7.316485176</accely>
</SensorValue>
<SensorValue>
<accelx>0.31103436</accelx>
<accely>7.70408184</accely>
</SensorValue>
</Values>
</ArrayOfRecord>
Code to parse the data:
import lxml.etree as etree
tree = etree.parse(r"C:\testdel.xml")
root = tree.getroot()
val_of_interest = root.findall('./Values/SensorValue')
for sensor_val in val_of_interest:
print sensor_val.find('accelx').text
print sensor_val.find('accely').text
I asked related question here: How to extract data from xml file that is deep down the tag
Thanks
The confusion was caused by the following default namespace (namespace declared without prefix) :
xmlns="http://schemas.datacontract.org/Storage"
Note that descendants elements without prefix inherit default namespace from ancestor, implicitly. Now, to reference element in namespace, you need to map a prefix to the namespace URI, and use that prefix in your XPath :
ns = {'d': 'http://schemas.datacontract.org/Storage' }
val_of_interest = root.findall('./d:Values/d:SensorValue', ns)
for sensor_val in val_of_interest:
print sensor_val.find('d:accelx', ns).text
print sensor_val.find('d:accely', ns).text

XML parsing specific values - Python

I've been attempting to parse a list of xml files. I'd like to print specific values such as the userName value.
<?xml version="1.0" encoding="utf-8"?>
<Drives clsid="{8FDDCC1A-0C3C-43cd-A6B4-71A6DF20DA8C}"
disabled="1">
<Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}"
name="S:"
status="S:"
image="2"
changed="2007-07-06 20:57:37"
uid="{4DA4A7E3-F1D8-4FB1-874F-D2F7D16F7065}">
<Properties action="U"
thisDrive="NOCHANGE"
allDrives="NOCHANGE"
userName=""
cpassword=""
path="\\scratch"
label="SCRATCH"
persistent="1"
useLetter="1"
letter="S"/>
</Drive>
</Drives>
My script is working fine collecting a list of xml files etc. However the below function is to print the relevant values. I'm trying to achieve this as suggested in this post. However I'm clearly doing something incorrectly as I'm getting errors suggesting that elm object has no attribute text. Any help would be appreciated.
Current Code
from lxml import etree as ET
def read_files(files):
for fi in files:
doc = ET.parse(fi)
elm = doc.find('userName')
print elm.text
doc.find looks for a tag with the given name. You are looking for an attribute with the given name.
elm.text is giving you an error because doc.find doesn't find any tags, so it returns None, which has no text property.
Read the lxml.etree docs some more, and then try something like this:
doc = ET.parse(fi)
root = doc.getroot()
prop = root.find(".//Properties") # finds the first <Properties> tag anywhere
elm = prop.attrib['userName']
userName is an attribute, not an element. Attributes don't have text nodes attached to them at all.
for el in doc.xpath('//*[#userName]'):
print el.attrib['userName']
You can try to take the element using the tag name and then try to take its attribute (userName is an attribute for Properties):
from lxml import etree as ET
def read_files(files):
for fi in files:
doc = ET.parse(fi)
props = doc.getElementsByTagName('Properties')
elm = props[0].attributes['userName']
print elm.value

Categories

Resources