问题
I have some issues with my script.
First of i wanna make sure that the correct name has been given by the user. For example if I were to write "Name" it should not match with anything in my xml. If i were to write "NameY" it should match with given name and not anything else(for example "NameX should not be matched). I tried using wordboundry but it did not help as I thought it would.
When I try want to change value in NameY the script changes for all the values(even for NameX). I believe this is because it can't seperate the "names"?
I am using argparse for this and the code is in another function.
- args.name = "the name to look for"
- args.dirname = "file location"
- args.value "the value I want to change to"
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"
My 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>
Edit fixed the problem by changning "is not None" to "== args.paramName"
来源:https://stackoverflow.com/questions/36015120/change-value-in-specific-child-element