使用Python编辑XML文件的childNodes中的所有文本

发布于 2024-10-31 05:39:35 字数 2359 浏览 6 评论 0原文

我试图通过将文本乘以用户输入的数字来编辑 XML 文件中名为“Volume”的所有标签内的文本。 “Volume”标签内的文本始终是数字。到目前为止,我的代码有效,但仅适用于“Volume”文本的第一个实例。

这是 XML 的示例:

         <blah>
                <moreblah> sometext </moreblah> ;
                <blah2>
                        <blah3> <blah4> 30 </blah4> <Volume> 15 </Volume> </blah3>
                </blah2>
        </blah>

         <blah>
                <moreblah> sometext </moreblah> ;
                <blah2>
                        <blah3> <blah4> 30 </blah4> <Volume> 25 </Volume> </blah3>
                </blah2>
        </blah>

这是我的 Python 代码:

#import modules
import xml.dom.minidom
from xml.dom.minidom import parse
import os
import fileinput

#create a backup of original file
new_file_name = 'blah.xml'
old_file_name = new_file_name + "_old"
os.rename(new_file_name, old_file_name)

#find all instances of "Volume"
doc = parse(old_file_name)
volume = doc.getElementsByTagName('Volume')[0]
child = volume.childNodes[0]
txt = child.nodeValue

#ask for percentage input
print
percentage = raw_input("Set Volume Percentage (1 - 100): ")
if percentage.isdigit():
    if int(percentage) <101 >1:
        print 'Thank You'

        #append text of <Volume> tag
        child.nodeValue = str(int(float(txt) * (int(percentage)/100.0)))

        #persist changes to new file
        xml_file = open(new_file_name, "w")
        doc.writexml(xml_file)
        xml_file.close()

        #remove XML Declaration
        text = open("blah.xml", "r").read()
        text = text.replace('<?xml version="1.0" ?>', '')  
        open("blah.xml", "w").write(text)


    else:

        print
        print 'Please enter a number between 1 and 100.'
        print 
        print 'Try again.'
        print
        print 'Exiting.'


        xml_file = open(new_file_name, "w")
        doc.writexml(xml_file)
        xml_file.close()

        os.remove(old_file_name)

我知道在我的代码中,我有“doc.getElementsByTagName('Volume')[0]”,它表示“Volume”标签的第一个实例,但我是只是这样做作为测试,看看它是否有效。所以我知道代码完全按照预期工作。但我想知道是否有人有任何建议,或者可以告诉我将用户输入百分比应用到“Volume”标签的所有实例的最简单方法。

这也是我第一次尝试 Python,所以如果你发现任何其他看起来奇怪的地方,请告诉我。

感谢您的帮助!

I'm trying to edit the text inside of all of the tags named "Volume" in an XML file by multiplying that text by a number entered by the user. The text inside of the "Volume" tag will always be a number. My code works so far, but only on the first instance of the "Volume" text.

Here's an example of the XML:

         <blah>
                <moreblah> sometext </moreblah> ;
                <blah2>
                        <blah3> <blah4> 30 </blah4> <Volume> 15 </Volume> </blah3>
                </blah2>
        </blah>

         <blah>
                <moreblah> sometext </moreblah> ;
                <blah2>
                        <blah3> <blah4> 30 </blah4> <Volume> 25 </Volume> </blah3>
                </blah2>
        </blah>

And here's my Python code:

#import modules
import xml.dom.minidom
from xml.dom.minidom import parse
import os
import fileinput

#create a backup of original file
new_file_name = 'blah.xml'
old_file_name = new_file_name + "_old"
os.rename(new_file_name, old_file_name)

#find all instances of "Volume"
doc = parse(old_file_name)
volume = doc.getElementsByTagName('Volume')[0]
child = volume.childNodes[0]
txt = child.nodeValue

#ask for percentage input
print
percentage = raw_input("Set Volume Percentage (1 - 100): ")
if percentage.isdigit():
    if int(percentage) <101 >1:
        print 'Thank You'

        #append text of <Volume> tag
        child.nodeValue = str(int(float(txt) * (int(percentage)/100.0)))

        #persist changes to new file
        xml_file = open(new_file_name, "w")
        doc.writexml(xml_file)
        xml_file.close()

        #remove XML Declaration
        text = open("blah.xml", "r").read()
        text = text.replace('<?xml version="1.0" ?>', '')  
        open("blah.xml", "w").write(text)


    else:

        print
        print 'Please enter a number between 1 and 100.'
        print 
        print 'Try again.'
        print
        print 'Exiting.'


        xml_file = open(new_file_name, "w")
        doc.writexml(xml_file)
        xml_file.close()

        os.remove(old_file_name)

I know that in my code, I have "doc.getElementsByTagName('Volume')[0]" which denotes the first instance of the "Volume" tag, but I was just doing that as a test to see if it would work. So I'm aware that the code is working exactly as it should. But I'm wondering if anyone has any suggestions, or could tell me the easiest way to apply the user input percentage to all of the instances of the "Volume" tag.

This is also my first attempt at Python, so if you see anything else that seems weird, please let me know.

Thank you for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流星番茄 2024-11-07 05:39:35

如果您使用更现代的 XML API,例如 ElementTree(在标准库中)或lxml(更高级)。

在 ElementTree 或 lxml 中,您可以访问 XPath(或类似的东西),它允许使用更灵活的语法来查找 XML 文档中的元素和属性。

在 ElementTree 中:

volumes = my_parsed_xml_file.find('.//Volume')

...将查找所有出现的 Volume 元素。

如果您坚持使用当前语法,请执行以下操作:

doc.getElementsByTagName('Volume')[0]

...您专门要求第零个(第一个)Volume。如果你想处理所有这些,你需要一个循环:

for volume in doc.getElementsByTagName('Volume'):
  child = volume.childNodes[0]
  // ... rest of your code inside the loop

如果你不熟悉像循环这样的结构,你可能应该退后一步并阅读入门编程指南,因为如果没有一些基础知识,事情很快就会变得非常复杂。祝你好运!

You'll be much happier if you use a more modern XML API, like ElementTree (in the standard library) or lxml (more advanced).

In ElementTree or lxml you get access to XPath (or something close), which allows for a much more flexible syntax in finding elements and attributes in XML documents.

In ElementTree:

volumes = my_parsed_xml_file.find('.//Volume')

...will find all occurrences of the Volume element.

If you stick with the current syntax, by doing:

doc.getElementsByTagName('Volume')[0]

...you're specifically asking for the zero-th (first) Volume. If you want to process them all, you want a loop:

for volume in doc.getElementsByTagName('Volume'):
  child = volume.childNodes[0]
  // ... rest of your code inside the loop

If constructs like loops are unfamiliar to you, you should probably step back and read an introductory programming guide, as things will get pretty complicated quickly without some fundamentals. Best of luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文