불행하게도, 나는 Excel에서 이러한 요소 내에서 요소 값이 아닌 속성을 가져 오는 것을 이전에 발견했다. 예를 들어 "stuff211"은 stuff211을 가져 오지만 stuff111은 가져 오지 않습니다. 이 기능은 Excel에서 작동하는 방식의 한계에 불과하다고 가정합니다. 가져 오기가 Excel에 있어야합니까, 아니면 Python과 같은 프로그래밍 언어를 사용할 수 있습니까? XML 파일에서 특정 엘리먼트와 애트리뷰트 값을 추출하기 전에 프로 시저를 작성 했으므로, 필자가 필요할 경우이를 찾아서 공유하게되어 기쁠까요?
UPDATE 여기
내가 작성 및 CSV 파일에 xml 파일에서 데이터를 제거하기 위해 이전에 사용했던 파이썬 스크립트입니다. 참고로 필자는 초기 특성상 파일에서 특정 데이터를 가져 오는 것만으로 모든 특성과 요소를 얻을 수 있도록 설정하지 않았습니다. search_items 전역 목록을 검색하려는 항목으로 편집해야합니다.
xml 파일의 경로에 대해 단일 인수를 사용하여 명령 줄에서 스크립트를 호출하거나 arg없이 사용할 수 있으며 디렉토리를 선택하라는 메시지가 표시됩니다. 문의 사항이 있으면 알려 주시기 바랍니다 :이 당신을 위해 작동
#!/usr/bin/python
# Change Ideas
# ------------
# Add option to get all xml elements/attributes
# Add support for json?
import sys, os, Tkinter, tkFileDialog as fd, traceback
# stop tinker shell from opening as only needed for file dialog
root = Tkinter.Tk()
root.withdraw()
# globals
debug_on = False
#get_all_elements = False
#get_all_attributes = False
# search items to be defined each time you run to identify values to search for.
# each item should have a search text, a type and optionally a heading e.g.
# search_items = ['exact_serach_text', 'item_type', 'column_heading(optional)']
# note: search items are case sensitive.
#
############################## E X A M P L E ##############################
search_items = [
['policyno=', 'xml_attribute', 'Policy No' ],
['transid=', 'xml_attribute', 'Trans ID' ],
['policyPremium=', 'xml_attribute', 'Pol Prem' ],
['outstandingBalance=', 'xml_attribute', 'Balance' ],
['APRCharge=', 'xml_attribute', 'APR Chrg' ],
['PayByAnnualDD=', 'xml_attribute', 'Annual DD' ],
['PayByDD=', 'xml_attribute', 'Pay by DD' ],
['mtaDebitAmount=', 'xml_attribute', 'MTA Amt' ],
['paymentMethod=', 'xml_attribute', 'Pmt Meth' ],
['ddFirstPaymentAmount=', 'xml_attribute', '1st Amt' ],
['ddRemainingPaymentsAmount=', 'xml_attribute', 'Other Amt' ],
['ddNumberOfPaymentsRemaining=', 'xml_attribute', 'Instl Rem' ],
]
item_types = ['xml_attribute', 'xml_element']
def get_heads():
heads = []
for i in search_items:
try:
# raise error if i[2] does not exist or is empty
assert len(i[2]) > 0, "No value in heading, use search text."
except:
heads.append(i[0]) # use search item as not heading is given
else:
heads.append(i[2])
return heads
def write_csv_file(path, heads, data):
"""
Writes data to file, use None for heads param if no headers required.
"""
with open(path, 'wb') as fileout:
writer = csv.writer(fileout)
if heads:
writer.writerow(heads)
for row in data:
try:
writer.writerow(row)
except:
print '...row failed in write to file:', row
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
for line in lines:
print '!!', line
print 'Data written to:', path, '\n'
def find_val_in_line(item, item_type, line):
if item_type.lower() == 'xml_element':
print 'Testing still in progress for xml elements, please check output carefully'
b1, b2 = ">", "<"
tmp = line.find(item) # find the starting point of the element value
x = line.find(b1, tmp+1) + len(boundary) # find next boundary after item
y = line.find(b2, x) # find subsequent boundary to mark end of element value
return line[x:y]
elif item_type.lower() == 'xml_attribute':
b = '"'
tmp = line.find(item) # find the starting point of the attribute
x = line.find(b, tmp+1) + len(b) # find next boundary after item
y = line.find(b, x) # find subsequent boundary to mark end of attribute
return line[x:y] # return value between start and end boundaries
else:
print 'This program does not currently support type:', item_type
print 'Returning null'
return None
def find_vals_in_file(file_path):
with open(file_path, "r") as f:
buf = f.readlines()
f.seek(0)
data, row = [], []
found_in_row, pos = 0, 0
l = len(search_items)
if debug_on: print '\nsearch_items set to:\n' + str(search_items) + '\n'
# loop through the lines in the file...
for line in buf:
if debug_on: print '\n..line set to:\n ' + line
# loop through search items on each line...
for i in search_items:
if debug_on: print '...item set to:\n ' + i[0]
# if the search item is found in the line...
if i[0] in line:
val = find_val_in_line(i[0], i[1], line)
# only count as another item found if not already in that row
try:
# do not increment cnt if this works as item already exists
row[pos] = val
if debug_on: print '.....repeat item found:- ' + i[0] + ':' + val
except IndexError:
found_in_row += 1 # Index does not exist, count as new
row.append(val)
if debug_on: print '....item found, row set to:\n ' + str(row)
# if we have a full row then add row to data and start row again...
if found_in_row == l:
if debug_on: print '......row complete, appending to data\n'
data.append(row)
row, found_in_row = [], 0
pos += 1 # start at 0 and increment 1 at end of each search item
pos = 0
f.close()
return data
def main():
path, matches = None, []
os.chdir(os.getenv('userprofile'))
# check cmd line args provided...
if len(sys.argv) > 1:
path = sys.argv[1]
else:
while not path:
try:
print 'Please select a file to be parsed...'
path = fd.askopenfilename()
except:
print 'Error selecting file, please try again.'
# search for string in each file...
try:
matches = find_vals_in_file(path)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print "An error occurred checking file:", path
print ''.join('!! ' + line for line in lines)
# write output to file...
if len(matches) == 0:
print "No matches were found in the files reviewed."
else:
heads = get_heads()
output_path = os.path.join(os.getcwd(),'tmp_matches.csv')
write_csv_file(output_path, heads, matches)
print "Please rename the file if you wish to keep it as it will be overwritten..."
print "\nOpening file..."
os.startfile(output_path)
if debug_on:
print "\nWriting output to screen\n", "-"*24
print heads
for row in matches:
print row
if __name__ == '__main__':
main()
희망. 지금까지 여러 xml 파일에 대해서만 테스트를 해봤지만 괜찮습니다.
빠른 응답을 보내 주셔서 감사합니다. 나는 그것을 Excel에서하는 것이 쉬워야한다고 생각했기 때문에 Excel을 위해 노력했습니다. 네가 가진 것을 나와 나눌 수 있다면 나는 영원히 감사 할 것이다. 나는 그것이 나를 위해 일하는 것을 볼 수있다, 시도에 해로움 :) –
문제 없음, 나는 내일 그것을 게시 할 것이다. 이미 파이썬을 설치 했습니까? 만약 당신이 http://www.python.org/download/에서 다운로드 할 수 없다면, 당신이 필요로하는 버전 등을 모른다면 알려주세요. – ChrisProsser
파이썬이 설치되지 않았기 때문에 나는 그것을 빨리 잡았습니다. 충분히 간단합니다. 이제는 이것으로 놀아야 만합니다. 이전에는 파이썬과 함께 일한 적이 없었습니다. 저는 제 일을 할 때만 자바를 사용합니다. 내일 당신의 후속 게시물을 찾을 것입니다. –