在 xml 中查找变量
find variable in xml
我有几个 xml 需要比较。问题是,其中有两个元素需要删除,因为它们总是不同的。
<section name="Cache">
<section name="Registry">
<key name="Expiration" description="Value range: 0 - &infin; Seconds" summary="Defines the registry entry cache expiration time" range="0-" type="integer" defaultvalue="300" modifiedby="user_x" modificationtime="2020-11-17T12:08:36.1900000+00:00" readonly="False" ismultivalue="False">300</key>
</section>
<section name="UserSession">
<key name="Expiration" description="Value range: 0 - &infin; Seconds" summary="Defines the session cache expiration time" range="0-" type="integer" defaultvalue="30" modifiedby="user_x" modificationtime="2020-11-17T12:08:36.1900000+00:00" readonly="False" ismultivalue="False">30</key>
</section>
</section>
modifiedby
是 xml 中的常量,因此我可以使用以下方法删除它:
tree = ET.parse(xml1)
root = tree.getroot()
xmlstr = ET.tostring(root, encoding='utf8', method='xml')
xmlstr = xmlstr.replace(b'user_x', b'')
但是我如何才能从 xml 中删除 modificationtime
,因为我知道这是一个无法预测的变量?这个modificationtime
returns在XML
的每个元素
最好在将其转换回字符串之前使用 ElementTree
进行所有替换,否则根本没有理由解析 XML:
import xml.etree.ElementTree as ET
tree = ET.parse(xml1)
root = tree.getroot()
# here we go
for key in root.findall('.//key'):
key.attrib['modifiedby'] = ''
key.attrib['modificationtime'] = ''
# and finally convert to bytestring
xmlstr = ET.tostring(root, encoding='utf8', method='xml') # add .decode() to get string
.//key
这里是 XPath 表达式,您可以在最新的 XML Path Language Standart 中阅读更多相关信息。它将帮助您调整代码以处理具有不同结构的 XML 文档。
我有几个 xml 需要比较。问题是,其中有两个元素需要删除,因为它们总是不同的。
<section name="Cache">
<section name="Registry">
<key name="Expiration" description="Value range: 0 - &infin; Seconds" summary="Defines the registry entry cache expiration time" range="0-" type="integer" defaultvalue="300" modifiedby="user_x" modificationtime="2020-11-17T12:08:36.1900000+00:00" readonly="False" ismultivalue="False">300</key>
</section>
<section name="UserSession">
<key name="Expiration" description="Value range: 0 - &infin; Seconds" summary="Defines the session cache expiration time" range="0-" type="integer" defaultvalue="30" modifiedby="user_x" modificationtime="2020-11-17T12:08:36.1900000+00:00" readonly="False" ismultivalue="False">30</key>
</section>
</section>
modifiedby
是 xml 中的常量,因此我可以使用以下方法删除它:
tree = ET.parse(xml1)
root = tree.getroot()
xmlstr = ET.tostring(root, encoding='utf8', method='xml')
xmlstr = xmlstr.replace(b'user_x', b'')
但是我如何才能从 xml 中删除 modificationtime
,因为我知道这是一个无法预测的变量?这个modificationtime
returns在XML
最好在将其转换回字符串之前使用 ElementTree
进行所有替换,否则根本没有理由解析 XML:
import xml.etree.ElementTree as ET
tree = ET.parse(xml1)
root = tree.getroot()
# here we go
for key in root.findall('.//key'):
key.attrib['modifiedby'] = ''
key.attrib['modificationtime'] = ''
# and finally convert to bytestring
xmlstr = ET.tostring(root, encoding='utf8', method='xml') # add .decode() to get string
.//key
这里是 XPath 表达式,您可以在最新的 XML Path Language Standart 中阅读更多相关信息。它将帮助您调整代码以处理具有不同结构的 XML 文档。