注释掉并取消注释xml元素

2024-03-29 14:44:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml文件,我想取消注释并注释掉文件中的一个元素。在

<my_element>
    <blablabla href="docs/MyBlank.htm" />
</my_element>

这个我想这样“结束”(评论一下):

^{pr2}$

在这个文件中,我有一个同名的元素,它是“closed”(注释掉),如下所示:

<!--
<my_element>
    <blablabla href="secretwebhacking/MySecrectBankLogin.htm" />
</my_element>
-->

我想“打开”它(取消注释),比如:

<my_element>
     <blablabla href="secretwebhacking/MySecrectBankLogin.htm" />
</my_element>

为此,我使用ElementTree,我知道如何编辑元素中的值和属性,但我根本不知道如何删除和添加一个特定元素周围的<!-- -->。在


Tags: 文件元素docsmy评论xmlelementhref
1条回答
网友
1楼 · 发布于 2024-03-29 14:44:18

您可以使用BeautifulSoup来进行解析。基本示例:

xmlbody = '<stuff>\
<my_element>\
    <blablabla href="docs/MyBlank.htm" />\
</my_element>\
<! \
<my_element>\
    <blablabla href="secretwebhacking/MySecrectBankLogin.htm" />\
</my_element>\
 >\
</stuff>'

from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(xmlbody, "lxml")

# Find all comments
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
for comment in comments:
  # Create new soup object from comment contents
  commentsoup = BeautifulSoup(comment, "lxml")
  # Find the tag we want
  blatag = commentsoup.find('blablabla')
  # Check if it is the one we need
  if(blatag['href']=="secretwebhacking/MySecrectBankLogin.htm"):
    # If so, insert the element within the comment into the document
    comment.insert_after(commentsoup.find('body').find('my_element'))
    # And remove the comment
    comment.extract()

# Find all my_elements
my_elements = soup.findAll('my_element')
for tag in my_elements:
  # Check if it's the one we want
  if(tag.find('blablabla')['href'] == "docs/MyBlank.htm"):
    # If so, insert a commented version
    tagcomment = soup.new_string(str(tag), Comment)
    tag.insert_after(tagcomment)
    # And remove the tag
    tag.extract()

print(soup.find('html').find('body').prettify().replace("<body>\n","").replace("\n</body>",""))

这应该是你的开始,你可以让它复杂到你需要。输出如下:

^{pr2}$

相关问题 更多 >