我的脚本存在一些问题。
首先,我想确保用户提供了正确的名称。例如,如果我写“Name”,它应该与我的xml中的任何内容都不匹配。如果我要写“NameY”它应该与给定的名称匹配而不是其他任何东西(例如“NameX不应该匹配)。我尝试使用wordboundry但它没有帮助,因为我认为它会。”
当我尝试更改NameY中的值时,脚本会更改所有值(即使对于NameX)。我相信这是因为它不能分开“名字”?
我正在使用argparse,代码在另一个函数中。
wordboundry = re.compile(r'(<NAME>(%s\b)<\/NAME>)' % args.name)
getName = ("{0}ROOTS/{0}ROOT/{0}ELEM/{0}SPEC/[{0}NAME]")
getDigit = ("{0}ROOTS/{0}ROOT/{0}ELEM/{0}SPEC/{0}DP/{0}NVP/[{0}CHECK]/[{0}DIGIT]")
for fileName in glob.glob(args.dirname):
print fileName
with open(fileName,"r") as file:
my_files_content = file.read()
if args.name in my_files_content: #instead of using args.name i was trying to use if re.search(wordboundry, my_files_content):
print "Parameter exist in this file\n"
tree = tree = ElementTree.ElementTree()
tree.parse(fileName)
ElementTree.register_namespace("", "http://something.com")
namespace = "{http://something.com}"
for names in tree.findall(getName.format(namespace)):
mathcName = names.find('{http://something.com}NAME').text
if mathcName == **args.paramName**:
for digits in tree.findall(getDigit.format(namespace)):
digitNumber = digits.find('{http://something.com}DIGIT').text
convertToString = ' '.join([str(mystring) for mystring in args.value]) #Convert to string
digits.find('{http://something.com}DIGIT').text = convertToString #This allows the script to changes the digit in the xml file
tree.write("test.xml", encoding='utf-8', xml_declaration=True)
else: print"NO MATCHES\n"
else:
print "i am not here"
else:
"Parameter does not exist in this file\n"
我的XML
<?xml version="1.0" encoding="utf-8"?>
<TOP xmlns="http://something.com">
<ROOTS>
<ROOT>
<ELEM>
<SPEC>
<NAME>NameX</NAME>
<DP>
<NVP>
<CHECK>NameX_1</CHECK>
<DIGIT>3</DIGIT>
</NVP>
<NVP>
<CHECK>NameX_2</CHECK>
<DIGIT>20</DIGIT>
</NVP>
</DP>
</SPEC>
<SPEC>
<NAME>NameY</NAME>
<DP>
<NVP>
<CHECK>NameY</CHECK>
<DIGIT>7</DIGIT>
</NVP>
</DP>
</SPEC>
</ELEM>
</ROOT>
</ROOTS>
</TOP>
编辑通过将“is not None”改为“== args.paramName”修复了问题