我有一个XML文件,并且希望用给定的attribute=value删除节点中的所有内容,但是无法使元素树.remove()方法工作。我得到一个list.remove(x): x not in list错误。
如果我有一个div,包含多个段落和列表元素,并具有属性v1-9,deleted,我希望能够删除整个div及其所有内容。
import xml.etree.ElementTree as ET
#get target file
tree = ET.parse('tested.htm')
#pull into element tree
root = tree.getroot()
#confirm output
print(root)
#define xlmns tags
MadCap = {'MadCap': 'http://www.madcapsoftware.com/Schemas/MadCap.xsd'}
i=1
j=6
# specify state
state = "state.deleted-in-vers"
# specify version
vers = "version-number.v{}-{}".format(i,j)
# combine to get conditional string might need to double up b/c of order mattering here???
search = ".//*[@MadCap:conditions='{},{}']".format(vers,state)
#get matching elements
for elem in root.findall(search, MadCap):
print('---PARENT---')
print(elem)
print('attributes:', elem.attrib)
print('text:', elem.text)
elem.text = " "
elem.attrib = {}
for child in elem.iter():
print('-child element-')
print(child)
elem.remove(child)
print('==========')为了简单起见,我省略了上面i和j上的循环。
下面是目标xml的一个片段,您可以看到这些属性是如何使用的。
<div MadCap:conditions="state.deleted-in-vers,version-number.v1-9">
<h4>Example with password prompts</h4>
<p>In the following example:</p>
<ul>
<li>We have included the value <code>connection.ask-pass</code>, so are being prompted for the password of the setup user. </li>
<li>This host has an installation user <code>hub-setup</code>. </li>
<li>We are installing to the host <code>hub.example.com</code>. We must provide the FQDN of the host.</li>
<li>The KeyStore we are installing to the <MadCap:variable name="Components/gateway-hub.gateway-hub-name" /> hosts is located at <code>/tmp/ssl_keystore</code> on the installation machine.</li>
<li>The TrustStore we are installing to the <MadCap:variable name="Components/gateway-hub.gateway-hub-name" /> hosts is located at <code>/tmp/ssl_truststore</code> on the installation machine.</li>
<li>We are not providing any of the password key-value pairs, and therefore are being prompted for the passwords. </li>
<li>This host has a runtime user <code>hub</code>.<ul><li>The runtime user is in group <code>gateway-hub</code>.</li></ul></li>
</ul>
<p>The <MadCap:variable name="3rd-party-products/formats.json-name" /> configuration file is the following:</p><pre xml:space="preserve">{
"connection": {
"ask_pass": true,
"user": "hub-setup"
},
"hosts": ["hub.example.com"],
"hub": {<MadCap:conditionalText MadCap:conditions="state.new-in-vers,version-number.v1-6">
"user" : "hub",
"group" : "gateway-hub",</MadCap:conditionalText>
"ssl": {
"key_store": "/tmp/ssl_keystore",
"trust_store": "/tmp/ssl_truststore"
}
}<MadCap:conditionalText MadCap:conditions="version-number.v1-6,state.deleted-in-vers">
"ansible" : {
"variables" : {
"hub_user": "hub",
"hub_group": "gateway-hub"
}
}</MadCap:conditionalText>
}</pre>
</div>
<div MadCap:conditions="state.deleted-in-vers,version-number.v1-9">
<h4>Example using SSH key</h4>
<p>In the next example:</p>
<ul>
<li>The SSH key for the setup user is located at <code>~/.ssh/HUB-SETUP-KEY.pem</code> on the installation machine, specified with <code>connection.private_key</code>. </li>
<li>The hosts have an installation user <code>hub-setup</code>. We must provide the FQDN of the host.</li>
<li>The hosts are specified in a list in a newline-delimited file at <code>/tmp/hosts</code> on the installation machine. </li>
<li>The KeyStore we are installing to the <MadCap:variable name="Components/gateway-hub.gateway-hub-name" /> hosts is located at <code>/tmp/ssl_keystore</code> on the installation machine.</li>
<li>The TrustStore we are installing to the <MadCap:variable name="Components/gateway-hub.gateway-hub-name" /> hosts is located at <code>/tmp/ssl_truststore</code> on the installation machine.</li>
<li>We are providing the passwords.</li>
<li>There is a runtime user on every host called <code>hub</code>.<ul><li>The runtime user is in group <code>gateway-hub</code>.</li></ul></li>
</ul>
<p>The <MadCap:variable name="3rd-party-products/formats.json-name" /> configuration file is the following:</p><pre xml:space="preserve">{
"connection": {
"private_key": "~/.ssh/HUB-SETUP-KEY.pem",
"user": "hub-setup"
},
"hosts_file": "/tmp/hosts",
"hub": {<MadCap:conditionalText MadCap:conditions="state.new-in-vers,version-number.v1-6">
"user" : "hub",
"group" : "gateway-hub",</MadCap:conditionalText>
"ssl": {
"key_store": "/tmp/ssl_keystore",
"key_store_password" "hub123",
"trust_store": "/tmp/ssl_truststore",
"trust_store_password": "hub123",
"key_password": "hub123"
}
}<MadCap:conditionalText MadCap:conditions="version-number.v1-6,state.deleted-in-vers">
"ansible" : {
"variables" : {
"hub_user": "hub",
"hub_group": "gateway-hub"
}
}</MadCap:conditionalText>
}</pre>
</div>发布于 2020-06-03 20:23:11
由于更容易删除元素,我发现使用lxml更容易完成任务。
尝试以下代码:
from lxml import etree as et
def remove_element(el):
parent = el.getparent()
if el.tail.strip():
prev = el.getprevious()
if prev is not None:
prev.tail = (prev.tail or '') + el.tail
else:
parent.text = (parent.text or '') + el.tail
parent.remove(el)
# Read source XML
parser = et.XMLParser(remove_blank_text=True)
tree = et.parse('Input.xml', parser)
root = tree.getroot()
# Replace the below namespace with your proper one
ns = {'mc': 'http://dummy.com'}
# Processing
for it in root.findall('.//*[@mc:conditions]', ns):
attr = it.attrib
attrTxt = ', '.join([ f'{key}: {value}'
for key, value in attr.items() ])
print(f'Elem.: {et.QName(it).localname:6}: {attrTxt}')
delFlag = False
cond = attr.get('{http://dummy.com}conditions')
if cond:
dct = { k: v for k, v in (x.split('.')
for x in cond.split(',')) }
vn = dct.get('version-number')
st = dct.get('state')
if vn == 'v1-6' and st.startswith('deleted'):
delFlag = True
print(f" {vn}, {st:15} {'Delete' if delFlag else 'Keep'}")
if delFlag:
remove_element(it)
# Print the result
print(et.tostring(tree, method='xml',
encoding='unicode', pretty_print=True))当然,在目标版本中,添加将此树保存到输出文件中。
为了正确格式化XML,使用单个根元素,我将您的内容封装在:
<main xmlns:MadCap="http://dummy.com">
...
</main>编辑
在我的前一个解决方案中,我使用it.getparent().remove(it)删除了所讨论的元素。但随后我发现了一个缺陷,如果源XML包含“混合内容”,即删除元素之后的“尾”文本(但不应该删除),该缺陷就会变得可见。
为了防止出现这种情况,我添加了remove_element函数,以删除只对元素本身进行并调用它,而不是以前的it.getparent().remove( it )。
注释中问题后面的解释
attrTxt的源是attr字典的内容(当前元素的属性)。这个片段实际上是在没有大括号的情况下打印这本字典的。它只用于追踪,在更远的地方被使用。
另一方面,离散余弦变换起着更重要的作用。它的源是cond,包含条件属性的内容(当前元素的),例如state.new-in-vers,version-number.v1.v1-6。
这段代码:
然后vn接收版本号(v1-6)和st -状态(新版本)。这是嵌在这里的大量情报。因为这两个片段都可以按不同的顺序发生,所以您不能创建任何匹配每个可能情况的XPath表达式。但是,如果检查上面的变量,就会发现这个元素是否应该是清除器。
https://stackoverflow.com/questions/62177550
复制相似问题