I am attempting to use Python’s ElementTree to parse and modify an xml file. The confusion comes with the XML Namespace. I can use the findall and finditer to get all of the servers names. However, I can't get the xpath query to work to find a specific server. instead the find just brings back the parent element.
What I need to do is find the correct server by the “name” or “machine” element and modify the “arguments”.
<? xml version=’1.0’ encoding=’UTF-8’?>
<domain xmlns=”http://xmlns.oracle.com.weblogic/domain”>
<server>
<name>Server1-rma</name>
<machine>server1</machine>
<server-start>
<arguments> -Xms4g</arguments>
</server-start>
</server>
<server>
<name>Server2-rma</name>
<machine>server2</machine>
<server-start>
<arguments> -Xms4g</arguments>
</server-start>
</server>
<server>
<name>Server3-rma</name>
<machine>server3</machine>
<server-start>
<arguments> -Xms4g</arguments>
</server-start>
</server>
</domain>
I have attempted various iterations of the query. However, I am new to XPath and must be doing something wrong:
Failed:
root + “ns0:server/[ns0:machine=’server2’]
Failed:
root + “ns0:server/ns0:[machine=’server2’]
Failed:
root + “ns0:server/[ns0:machine=ns0:’server2’]
sample code:
import xml.etree.ElementTree as ET
namespace = {‘ns0’: ‘ http://xmlns.oracle.com.weblogic/domain’}
tree = ET.parse(‘config.xml’)
root = tree.getroot()
for item in root.find((root + “ns0:server/[ns0:machine=’server2’]), namespace)
print(item.tag)
output:
{http://xmlns.oracle.com.weblogic/domain}server
I was hoping be able to match the "machine" element and pull the parent element in order to access the correct "arguments" element.
I am a beginner at xpath and elementtree so I am positive, that I am just doing something incorrectly. I am just not sure what. Any help would be greatly appreciated.
/ns0:domain/ns0:server[ns0:machine='server2']. The Predicate is part of the same Location Step. Also, do note thatElementTreefromxml.etreemodule has limited support for XPath 1.0