簡體   English   中英

使用python注釋xml標簽

[英]using python commenting xml tags

對於下面的xml文件,我如何使用python注釋(在xml中)標題標簽及其子標簽? 我是python的新手,嘗試使用lxml但只能添加新注釋,而不能注釋現有標簽。 請幫忙,謝謝

<note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
<body>Don't forget me this weekend!</body>
</note>

我希望輸出像

<note>
<to>Tove</to>
<from>Jani</from>
<!--  <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>

Python中的注釋以井號字符#開頭,並延伸到物理行的末尾。 注釋可能會出現在行的開頭或空格或代碼之后,但不能出現在字符串文字中。 字符串文字中的哈希字符只是哈希字符。 由於注釋是為了澄清代碼,而不是由Python解釋,因此在鍵入示例時可以將其省略。

<note>
<to>Tove</to>
<from>Jani</from>
#<heading> Reminder
#    <security>level  1</security>
#</heading>
<body>Don't forget me this weekend!</body>
</note>

這里是Python非正式介紹的鏈接。

如果我在您的問題中遺漏了一些東西,這里有一些有關如何提出問題的信息 ,以及如何創建最小,完整和可驗證的示例,以及有關導覽的信息 (以防您尚未看到它)。

祝好運!

嘗試類似

with open('test.xml', 'r+') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
    if '<heading>' or '</heading>' in line :
            line = line.replace('<heading>', '<-- <heading>').replace('</heading>', '</heading> -->')
    f.write(line)

這是一個使用內置ElementTree庫和xml示例作為輸入文件的示例:

from xml.etree import ElementTree as et

tree = et.parse('test.xml')
note = tree.getroot()

# Locate the heading and preserve the whitespace after the closing tag
heading = note.find('heading')
tail = heading.tail

# Generate the comment string with a space before and after it.
heading.tail = ' '
heading_comment = ' ' + et.tostring(heading,'unicode')

# Generate the comment node with the text of the commented out node and its original whitespace tail.
comment = et.Comment(heading_comment)
comment.tail = tail

# Locate the location in the child list of the heading node,
# remove it, and replace with the comment node.
index = note.getchildren().index(heading)
note.remove(heading)
note.insert(index,comment)

tree.write('out.xml')

輸出文件:

<note>
<to>Tove</to>
<from>Jani</from>
<!-- <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM