在xml中使用python将文本节点替换为另一个

2024-06-16 13:03:31 发布

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

这是我的xml文件:

<?xml version="1.0" encoding="UTF-8" ?> 
<raml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="raml21.xsd">
<cmData type="actual" scope="all" name="plan_file">
<header>
 <log dateTime="2011-05-18T04:05:02" action="created" /> 
</header>
<managedObject class="Fruit">
 <p name="Apple">100</p> 
 <p name="Mango">4</p> 
 <p name="Pear">99</p> 
 <p name="Jackfruit">67</p> 
 <p name="Strawberry">200</p> 
 <p name="Guava">100</p> 
 <p name="Banana">100</p> 
 <p name="Breadfruit">1500</p> 
 <p name="Musambi">100</p> 
</managedObject>
</cmData>
</raml>

我要做的就是这样。我需要用另一个数字(在运行时通过pythonshell输入)替换给定属性的文本节点(100,4,99)。我需要一个单独的xml文件与更改的值。在

我编写了python脚本,如下所示:

^{pr2}$

既然我用这个表达式

newcontent = content.replace(name[2].firstChild.nodeValue, str(parameter_value))

此脚本正在运行,但使用此脚本(因为我使用的是名称[2]),我只能更改xml文件的索引2,即,梨。如果我写1而不是2,我可以改变芒果的值,等等。 但我需要把剧本写得通俗些。我该如何修改脚本???在

谢谢你的帮助。。:)


Tags: 文件name脚本httpversionwwwxmlraml
1条回答
网友
1楼 · 发布于 2024-06-16 13:03:31

我注意到您使用的是python3(input())而不是python2(raw_input())。在

您到底为什么要使用正则表达式(re模块)?据我所知,您正在尝试将一个XML文件解析为DOM,找到一个由其name属性标识的<p>元素,用用户提供的文本替换其文本,并将其写入一个新文件。通过操作DOM比尝试在原始XML流上运行正则表达式,可以更可靠地完成替换。下面的Python 3程序演示如何操作DOM:

#!/usr/bin/env python3
from xml.dom import minidom
import os.path

def new_value(parameter, parameter_value, target_dir, inputfile):
    # Load the XML file and parse it
    dom = minidom.parse(inputfile)

    # Find all <p> elements with the correct name= attribute
    els = [element
           for element in dom.getElementsByTagName('p')
           if element.getAttribute('name') == parameter]

    # Choose the first among these
    chosen_el = els[0]

    # Set its text content
    if chosen_el.hasChildNodes:
        # Assumes that the first child is in fact a text node
        chosen_el.firstChild.nodeValue = parameter_value
    else:
        # If the element is empty, add a child node
        chosen_el.appendChild(dom.createTextNode(parameter_value))

    fullname = os.path.join(target_dir, "test" + str(parameter_value) + ".xml")

    # Opening a file using a "with open" block automatically
    # closes it at the end of the block
    with open(fullname, 'wb') as outFile:
        outFile.write(dom.toxml('utf-8'))

parameter = input("Enter the parameter: ")              # or 'Mango'
target_dir = input("Enter the target directory: ")      # or '.'
input_file = input("Enter the input file: ")            # or 'so_xml.xml'
parameter_value = input("Enter the value to replace: ") # or 'Manstop'
new_value(parameter, parameter_value, target_dir, input_file)

相关问题 更多 >