使用python注释xml标签

时间:2017-12-06 12:09:02

标签: python xml

对于下面的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>

3 个答案:

答案 0 :(得分:0)

  

Python中的注释以哈希字符return ( <select> {this.state.isLoadingInputDropDown ? <option value="-1" disabled >Loading...</option> : [{ id: -1, name: '--Select a Accessorial Charge first --'}, ...this.state.allInputs].map( (input) => (<option value={input.id} key={input.id}>{input.name}</option>) )} </select> ) 开头,并扩展为   物理线的末端。评论可能会出现在a的开头   行或跟随空格或代码,但不在字符串文字中。   字符串文字中的哈希字符只是一个哈希字符。   由于注释是为了澄清代码而不是由Python解释,   在输入示例时可能会省略它们。

#

以下是指向An Informal Introduction to Python的链接。

如果我在您的问题中遗漏了某些内容,以下是有关How to ask a question以及How to create a Minimal, Complete, and Verifiable exampletour的一些信息,以防您没有看到了它。

祝你好运!

答案 1 :(得分:0)

尝试类似

的内容
{{1}}

答案 2 :(得分:0)

Here's an example using the built-in ElementTree library and your xml sample as the input file:

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')

Output file:

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