Python-使用regex-re.sub在2个节点之间更新xml值不起作用

Python-使用regex-re.sub在2个节点之间更新xml值不起作用,python,regex,xml,Python,Regex,Xml,我想更改2个xml节点之间的值-设置_状态 filedata是此xml行所在的文本 <ws:genericAction>SET_STATUS</ws:genericAction> SET_状态 为此,regex写道: re.sub(r'<\/ws:genericAction>\s*(.*)(?=\n<\/ws:genericAction>)', "New Text", filedata, flags=re.IGNORECASE) re.sub

我想更改2个xml节点之间的值-设置_状态 filedata是此xml行所在的文本

<ws:genericAction>SET_STATUS</ws:genericAction>
SET_状态
为此,regex写道:

re.sub(r'<\/ws:genericAction>\s*(.*)(?=\n<\/ws:genericAction>)', "New Text", filedata, flags=re.IGNORECASE)
re.sub(r'\s*(*)(?=\n)”,“新文本”,filedata,flags=re.IGNORECASE)
所有节目:

with open("createUser.txt", 'r') as file:
    filedata = file.read()
re.sub(r'<\/ws:genericAction>\s*(.*)(?=\n<\/ws:genericAction>)', "New Text", filedata, flags=re.IGNORECASE)
with open("createUser.txt", 'w') as file:
    file.write(filedata)
打开(“createUser.txt”,“r”)作为文件:
filedata=file.read()
re.sub(r'\s*(.*)(?=\n)”,“新文本”,filedata,flags=re.IGNORECASE)
打开(“createUser.txt”,“w”)作为文件:
file.write(文件数据)
感谢您的帮助

re.sub()
不会就地修改字符串,而是在替换后返回字符串:

filedata = re.sub(r'(<ws:genericAction>)([^<>]+)(?=<\/ws:genericAction>)', "\\1New Text", filedata, flags=re.IGNORECASE)
filedata=re.sub(r'()([^]+)(?=)',“\\1新文本”,filedata,flags=re.IGNORECASE)

带有解析器的解决方案:

from lxml import etree

# our test string
xml = '''<root xmlns:ws="http://example.com">
            <ws:genericAction>SET_STATUS</ws:genericAction>
        </root>'''

# the dom
root = etree.fromstring(xml)

# our item(s) as an xpath expression
item = root.xpath(".//ws:genericAction[text()='SET_STATUS']", namespaces = {'ws': 'http://example.com'})

# modify the first one
item[0].text = "Something new here"

# print the new dom
etree.tostring(root, pretty_print=True)
从lxml导入etree
#我们的测试字符串
xml=“”
设置您的状态
'''
#大教堂
root=etree.fromstring(xml)
#我们的项作为xpath表达式
item=root.xpath(“.//ws:genericAction[text()='SET_STATUS']”,命名空间={'ws':'http://example.com'})
#修改第一个
项[0]。text=“此处有新内容”
#打印新的dom
etree.tostring(root,pretty\u print=True)
这就产生了

b'<root xmlns:ws="http://example.com">
      <ws:genericAction>Something new here</ws:genericAction>
  </root>'
b'
这里有些新东西
'

使用解析器,例如,
lxml
。谢谢,在这样做之后,我的所有行都消失在“新文本”中,是否有办法提供只替换标记之间文本的正则表达式?设置_STATUS@Start,它应该成为新文本,对吗?是的,正是我想要的achieve@Start,好的,要替换标记之间的简单文本,请使用“我的更新”。但是使用xml解析器处理xml要好得多documents@Start,在我的回答中。检查它这个解决方案的问题是,如果我想在第一次迭代后给它另一个参数,它将找不到,这是因为他只查找[text()='SET_STATUS'],这就是为什么换行文本的正则表达式更有效。@Start:我怀疑正则表达式本身是否“更有效”。您可以将正则表达式与
lxml
结合使用。