첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
6.15MB

▶ book.xml

<?xml version="1.0" ?>
<booklist cnt="3">
    <book ISBN="0399250395">
        <title>The Very Hungry Caterpillar Pop-Up Book</title>
        <author name="Eric Carle"  />
        <author name="Keith Finch" />
        <publisher> Philomel Books</publisher>
        <description> Celebrating the 40th anniverary of one of the most popular children's books ever created</description>
    </book>
    <book ISBN="0964729237">
        <title lang="english">The Shack</title>
    </book>
    <book ISBN="0553281097">
        <title>You Can Negotiate Anything</title>
        <author name="Herb Cohen" />
        <category cid="12">Negotiate and narrative skill</category>
    </book>
</booklist>

 

300x250

 

▶ main.py

import xml.dom.minidom
import xml.etree.ElementTree

##################################################
# 전역 변수
##################################################

loopFlag = 1

fileDescriptor = -1

document = None

##################################################
# 공통
##################################################

def PrintMenu():
    print()
    print("==================================================")
    print("도서 관리 프로그램 메뉴")
    print("==================================================")
    print("[l] XML 파일 로드하기"   )
    print("[p] XML 출력하기"        )
    print("[b] 도서명 목록 출력하기")
    print("[a] 새 도서 추가하기"    )
    print("[e] 도서명 검색하기"     )
    print("[m] HTML 출력하기"       )
    print("[q] 프로그램 종료하기"   )
    print("==================================================")

def ExecuteFunction(menuKey):
    global document
    if menuKey == "l":
        document = LoadXMLFile()
    elif menuKey == "p":
        PrintXML()
    elif menuKey == "b":
        PrintBookTitleList()
    elif menuKey == "a":
        print()
        newISBN  = str(input("IBSN 코드를 입력해 주시기 바랍니다 : "))
        newTitle = str(input("도서명을 입력해 주시기 바랍니다 : "   ))
        AddBook({"ISBN" : newISBN, "title" : newTitle})
    elif menuKey == 'e':
        print()
        keyword = str(input("검색할 도서명 키워드를 입력해 주시기 바랍니다 : "))
        print()
        PrintBookList(GetBookTupleList(keyword))
    elif menuKey == 'm':
        print()
        keyword = str(input ("HTML 출력을 위한 도서명 키워드를 입력해 주시기 바라니다 : "))
        print()
        html = GetHTML(GetBookTupleList(keyword))
        print("========================================")
        print(html)
        print("========================================")
    elif menuKey == 'q':
        ExitApplication()
    else:
        print ("에러 : 알 수 없는 메뉴 키를 입력하셨습니다!")

def CheckDocument():
    global document
    if document == None:
        print("에러 : 도큐먼트가 설정되지 않았습니다!")
        return False
    return True

##################################################
# XML 파일 로드하기
##################################################

def LoadXMLFile():
    print()
    filePath = str(input("XML 파일 경로를 입력해 주시기 바랍니다 : "))
    global fileDescriptor
    print()
    try:
        fileDescriptor = open(filePath)
    except IOError:
        print("파일명 또는 경로가 적절하지 않습니다.")
        return None
    else:
        try:
            document = xml.dom.minidom.parse(fileDescriptor)
        except Exception:
            print("파일 로딩시 에러가 발생했습니다.")
        else:
            print("XML 파일을 로드했습니다.")
            return document
    return None

##################################################
# XML 출력하기
##################################################

def PrintXML():
    if CheckDocument():
        print()
        print("========================================")
        print(document.toxml())
        print("========================================")

##################################################
# 도서명 목록 출력하기
##################################################

def PrintBookTitleList():
    global document
    if not CheckDocument():
        return None
    print()
    booklistElement = document.childNodes[0]
    for node in booklistElement.childNodes:
        if node.nodeName == "book":
            for childNode in node.childNodes:
                if childNode.nodeName == "title":
                    print("도서명 :", childNode.firstChild.nodeValue)

##################################################
# 새 도서 추가하기
##################################################

def AddBook(bookDictionary):
    global document

    if not CheckDocument() :
        return None

    bookElement = document.createElement("book")

    bookElement.setAttribute("ISBN", bookDictionary["ISBN"])

    titleText = document.createTextNode(bookDictionary["title"])

    titleElement = document.createElement("title")

    titleElement.appendChild(titleText)

    bookElement.appendChild(titleElement)

    booklistElement = document.firstChild

    booklistElement.appendChild(bookElement)

##################################################
# 도서명 검색하기
##################################################

def GetBookTupleList(keyword):
    global document

    if not CheckDocument():
        return None

    try:
        elementTree = xml.etree.ElementTree.fromstring(str(document.toxml()))
    except Exception:
        print ("엘리먼트 트리 파싱시 에러 : XML 문서가 정확하지 않습니다!")
        return None

    bookTupleList = []

    bookElementIterator = elementTree.iter("book")

    for bookElement in bookElementIterator:
        titleElement = bookElement.find("title")
        if titleElement.text.find(keyword) >= 0:
            bookTupleList.append((bookElement.attrib["ISBN"], titleElement.text))

    return bookTupleList

def PrintBookList(bookTupleList):
    for bookTuple in bookTupleList:
        print(bookTuple)

##################################################
# HTML 출력하기
##################################################

def GetHTML(bookTupleList):
    domImplementation = xml.dom.minidom.getDOMImplementation()

    newDocument = domImplementation.createDocument(None, "html", None)

    headerElement = newDocument.createElement("header")

    rootElement = newDocument.documentElement

    rootElement.appendChild(headerElement)

    bodyElement = newDocument.createElement("body")

    for bookTuple in bookTupleList:

        bElement = newDocument.createElement("b")

        ibsnText = newDocument.createTextNode("ISBN : " + bookTuple[0])

        bElement.appendChild(ibsnText)

        bodyElement.appendChild(bElement)

        brElement = newDocument.createElement("br")

        bodyElement.appendChild(brElement)

        pElement = newDocument.createElement("p")

        titleText = newDocument.createTextNode("도서명 : " + bookTuple[1])

        pElement.appendChild(titleText)

        bodyElement.appendChild(pElement)
        bodyElement.appendChild(brElement)

    rootElement.appendChild(bodyElement)

    return newDocument.toxml()

##################################################
# 프로그램 종료하기
##################################################

def UnlinkDocument():
    global document
    if document != None:
        document.unlink()

def ExitApplication():
    global loopFlag
    loopFlag = 0
    UnlinkDocument()

##################################################
# 프로그램 종료하기
##################################################

if __name__ == "__main__":
    while(loopFlag > 0):
        PrintMenu()
        print()
        menuKey = str(input("메뉴를 선택해 주시기 바랍니다 : "))
        ExecuteFunction(menuKey)
    else:
        print()
        print("프로그램을 종료합니다.")
        print()
728x90
반응형
그리드형(광고전용)
Posted by icodebroker
TAG ,

댓글을 달아 주세요