문제

I am currently using lxml for XSLT transformation in python. After transformation I have to write the content to different files. For better understanding my code is here as follows:

    ##function to create a new file and write the result into the file 
    def  new_file(a,b):
        full_path = 'path of teh folder to create the file'+a
        file_new = open(full_path, 'w')
        file_new.write(b)


    if xmlRoot.xpath('//slide[@nav_lvl_1="x" and @nav_lvl_2="y"]'):

        ##xpath to get the all the selected nodes of the attributes x and y
        slide_list = xmlRoot.xpath('//slide[@nav_lvl_1="x" and @nav_lvl_2="y"]')

        ##loop against the obtained list of node element
        for each_slide in slide_list:
            xslRoot = etree.parse('path of xsl_file')
            transform = etree.XSLT(xslRoot)
            newdom = transform(xmlRoot)
            file_name =  ('slide'+each_slide.get('page_number')+'.xml')
            result = etree.tostring(newdom, pretty_print=True)
            print etree.tostring(newdom, pretty_print=True)
            new_file(file_name , result)

The following code works absolutely fine but, when I call the function to create the file and write the result into it, it writes the whole result into the file instead of theloop part of the result.

For example: If i have five node elements in slide_list then, the file xslRoot gets transformed five times for different values. And for each transform I have to write the result in five different files. When I run this code I have all five transformed results in all five files that is created, where i need only one result per file.

What is the mistake i have done. NOt able to figure out. any suggestions?

input Xml would be :

- <slide add_info="Merchandising" name="slide8.xml" nav_lvl_1="x" nav_lvl_2="y" page_number="8">
    and ....

- <slide add_info="Merchandising" name="slide8.xml" nav_lvl_1="x" nav_lvl_2="y" page_number="9">
    and ...

- <slide add_info="Merchandising" name="slide8.xml" nav_lvl_1="x" nav_lvl_2="y" page_number="10">
    and ...

- <slide add_info="Merchandising" name="slide8.xml" nav_lvl_1="x" nav_lvl_2="y" page_number="11">

    and so on...
도움이 되었습니까?

해결책

I think the problem is that you are loading the whole file into result on each iteration of the loop. The only reference to the current iteration is when you assign the file name:

file_name =  ('slide'+each_slide.get('page_number')+'.xml')

other than this 'each_slide' is not referred to anywhere to obtain a subset of the document rather than the whole thing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top