2011-06-14 10 views
1

elementtree를 사용하여 XML 파일을 구문 분석하려고합니다. 그러나 내가 읽으려는 XML 파일은 MySql에서 내보내졌고 데이터베이스에 항목이있는 경우 XML 파일이 만들어 질 때 c : cygwin \ bin과 같이 '\ b'를 백 스페이스로 변환합니다. 어쨌든 XML 파일에서 '\ b'의 모든 항목을 삭제하려고하므로 elementtree.parse() 메소드를 통해 보낼 수 있습니다. 그리고 어떤 이유로 '\ b'의 모든 항목을 제거한 후에 전체 파일을 쓰지 않을 것입니다. 여기XML 파일 덮어 쓰기

내가 뭐하는 거지입니다 :

def preprocess(file): 
    #exporting from MySQL query browser adds a weird 
    #character to the result set, remove it 
    #so the XML parser can read the data 
    print "in preprocess" 
    lines = map(lambda line: line.replace("\b", " "), file) 

    #go to the beginning of the file 
    file.seek(0); 

    #overwrite with correct data 
    file.writelines(lines) 
    sys.exit() 


'''Entry into the program''' 
#test the file to see if processing is needed before parsing 
for line in xml_file: 
    p = re.compile("\\b") #search for '\b' 
    if(p.match(line)): 
     processing = True 
     break #only one match needed 

if processing: 
    preprocess(xml_file) 

결과는 내가 잘라 헤더가있는 XML 파일과 함께 결국, 그래서 파서에 전달 때 실패합니다.

는 XML 파일에서 절단됩니다 것입니다 :

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE ROOT SYSTEM "diskreport.dtd"> 
<ROOT> 
    <row> 
     <field name="buildid">26960</field> 
     <field name="cast(status as char)">Filesystem   1K-blocks  Used Available Use% Mounted on 
C:cygwinin  285217976 88055920 197162056 31% /usr/bin 

어떤 도움/아이디어, 내가보고 p.match를 사용하고, 끝내 내가 문제를 파악

+0

왜 '와 \\'각'\'를 대체하지? 이렇게하면 다른 이스케이프 문자열 (예 : 경로에'\ t','\ n' 등이 포함 된 경우)에 문제가 발생하지 않습니다. – multipleinterfaces

+0

XML 파일을 내보내는 데이터베이스의 데이터는 여기에서 서버에서 실행되는 많은 스크립트는 실행 가능한 데이터가 아닙니다. –

+0

그는''\ b''를'' "''로 바꾸는 대신' '\''을' '\ '대신' – Santa

답변

1

감사 것 '\ b'는 p.search를 사용해야 할 때 정말로 필요합니다. p.match는 행의 처음부터 만 보이고, search는 전체 행에서 occurences를 찾습니다.

솔루션 :

def preprocess(file): 
    #exporting from MySQL query browser adds a weird 
    #character to the result set, remove it 
    #so the XML parser can read the data 
    print "in preprocess" 
    lines = map(lambda line: line.replace("\b", ""), file) 

    #go to the beginning of the file 
    file.seek(0); 

    #overwrite with correct data 
    file.writelines(lines) 
    sys.exit() 


'''Entry into the program''' 
#test the file to see if processing is needed before parsing 
for line in xml_file: 
    p = re.compile("\\b") 
    if(p.search(line)): ####Changed to p.search here 
     processing = True 
     break #only one match needed 

if processing: 
    preprocess(xml_file) 
+0

참고 : 올 바르고 작동하면 사용자 자신의 대답을 수락 할 수 있습니다 – Shahbaz