Osho
Osho

Reputation: 168

Python replace() in XML file

I am facing with another problem.

I have kind of XML file with example code:

<case classname="perf" name="device">
    <Type>GET</Type>
    <Name>xxx</Name>
    <Request>Something</Request>
</case>

<case2 name="device_n>
    <Type>GET</Type>
    <Name>yyy</Name>
    <Request>Something</Request>
</case2>

<case...n>
...
</case...n>

How can I replace xxx to be named 'device' and yyy in case2 to be device_n?

I think something like that could be OK, but don't know how to write it:

with open('some_xml.xml') as parsed:
    if line in parsed.readlines.startswith("name="):
        line.replace('', "name=... #what's now?

This should be somekind of iterator because I have a lot of cases.

Upvotes: 0

Views: 247

Answers (2)

balderman
balderman

Reputation: 23815

A different approach (using xml parsing)

import xml.etree.ElementTree as ET

to_replace = {".//case/Name":'device',".//case2/Name":'device_n'}
xml = '''<r>
<case classname="perf" name="device">
    <Type>GET</Type>
    <Name>xxx</Name>
    <Request>Something</Request>
</case>

<case2 name="device_n">
    <Type>GET</Type>
    <Name>yyy</Name>
    <Request>Something</Request>

 </case2>
  </r>'''
root = ET.fromstring(xml)
for x_path,new_val in to_replace.items():
  ele = root.find(x_path)
  ele.text = new_val
ET.dump(root)

output

<r>
<case classname="perf" name="device">
    <Type>GET</Type>
    <Name>device</Name>
    <Request>Something</Request>
</case>

<case2 name="device_n">
    <Type>GET</Type>
    <Name>device_n</Name>
    <Request>Something</Request>

 </case2>
  </r>

Upvotes: 0

Mike67
Mike67

Reputation: 11342

There may be a more clever way to do this with regex, but basic string searching seems to work:

import io

data = '''
<case classname="perf" name="device">
    <Type>GET</Type>
    <Name>xxx</Name>
    <Request>Something</Request>
</case>

<case2 name="device_n">
    <Type>GET</Type>
    <Name>yyy</Name>
    <Request>Something</Request>
</case2>'''

strOut="" # new string
f = io.StringIO(data)  # load string data as file text
for rowx in f:  # each line in data
    row = rowx.rstrip()  # remove newline
    if ' name="' in row: # <case name=...>
        nm = row[row.index(' name="')+7:len(row)-2] # get name
    if "<Name>" in row and nm:  # <Name>....
        idx = row.index("<Name>") + 6
        strOut += row[:idx] + nm + "</Name>\n"  # set name field here
        nm = ""  # in case bad block, don't copy wrong name
    else:
        strOut += row + "\n"  # copy line to new string

print(strOut)

Output

<case classname="perf" name="device">
    <Type>GET</Type>
    <Name>device</Name>
    <Request>Something</Request>
</case>

<case2 name="device_n">
    <Type>GET</Type>
    <Name>device_n</Name>
    <Request>Something</Request>
</case2>

Upvotes: 2

Related Questions