0

我有一个自动化过程,可以根据外部数据源使 XML 文件保持最新。此 XML 文件也可以由用户修改,需要维护他们的手动更改。

<Nodes>
    <!-- User added data goes here -->
    <Node name="1">Data Data Data</Node>
    <Node name="2">Data Data Data</Node>
    <Node name="3">Data Data Data</Node>

    <!-- AUTOMATEDSTUFF -->
    <!-- User, do not modify nodes below this line. -->
    <Node name="4">Data Data Data</Node>
    <Node name="5">Data Data Data</Node>
    <Node name="6">Data Data Data</Node>

</Nodes>

在文件的每次更新时,我都想删除以前由我的自动化添加的所有节点。这是以下所有内容:

<!-- AUTOMATEDSTUFF --> 

现在我正在阅读 Python 中的所有节点,如下所示:

xmldoc = minidom.parse(filename)
nodesSection = xmldoc.getElementsByTagName('Nodes')[0]
for child in nodesSection.childNodes:
    .....

如何在遇到我的评论后才开始寻找节点?

4

1 回答 1

3

In XML, comments are comments, and can be rightfully stripped out of the document in any stage of processing. You should adapt your program to add a special attribute, like

<Nodes>
    <!-- User added data goes here -->
    <Node name="1">Data Data Data</Node>
    <Node name="2">Data Data Data</Node>
    <Node name="3">Data Data Data</Node>

    <!-- User, do not modify nodes below this line. -->
    <Node name="4" from="autogenerated">Data Data Data</Node>
    <Node name="5" from="autogenerated">Data Data Data</Node>
    <Node name="6" from="autogenerated">Data Data Data</Node>
</Nodes>

Then, you can simply filter out all nodes with the property from="autogenerated".


However, if you really want to detect comments (and as mentioned above, that's a bad idea), simply check all children of <Node>:

xmldoc = minidom.parse(filename)
nodes = xmldoc.documentElement.childNodes
commentIdx = next(i for i,n in enumerate(nodes) if
                n.nodeType == n.COMMENT_ELEMENT and n.data == ' AUTOMATEDSTUFF ')
automatedNodes = nodes[commentIdx+1:]
print(automatedNodes) # or do something else with them
于 2012-01-04T18:51:20.947 回答