[PYTHON/COMMON] defusedxml 패키지 설치하기
■ defusedxml 패키지를 설치하는 방법을 보여준다. 1. 명령 프롬프트를 실행한다. 2. 명령 프롬프트에서 아래 명령을 실행한다. ▶ 실행 명령
1 2 3 |
pip install defusedxml |
■ defusedxml 패키지를 설치하는 방법을 보여준다. 1. 명령 프롬프트를 실행한다. 2. 명령 프롬프트에서 아래 명령을 실행한다. ▶ 실행 명령
1 2 3 |
pip install defusedxml |
■ ElementTree 클래스의 getroot 메소드를 사용해 루트 엘리먼트를 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from xml.etree.ElementTree import ElementTree, Element, SubElement, dump noteElement = Element("note") noteElement.attrib["date"] = "20171219" SubElement(noteElement, "to" ).text = "Tove" SubElement(noteElement, "from" ).text = "Jani" SubElement(noteElement, "heading").text = "Reminder" SubElement(noteElement, "body" ).text = "Don't forget me this weekend!" elementTree = ElementTree(noteElement) print(elementTree.getroot()) """ <Element 'note' at 0x0000024A9BD03E20> """ |
■ Element 클래스의 attrib 속성을 사용해 어트리뷰트를 추가하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from xml.etree.ElementTree import Element, SubElement, dump noteElement = Element("note") noteElement.attrib["date"] = "20240506" toElement = Element("to") toElement.text = "Duke" noteElement.append(toElement) SubElement(noteElement, "from").text = "James" dump(noteElement) """ <note date="20240506"><to>Duke</to><from>James</from></note> """ |
■ dump 함수 : XML 문자열 출력하기 ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from xml.etree.ElementTree import Element, dump noteElement = Element('note') toElement = Element('to') toElement.text = 'Tove' noteElement.append(toElement) dump(noteElement) """ <note><to>Tove</to></note> """ |
■ XmlNamespaceMapping 엘리먼트를 사용해 XML 네임스페이스를 바인딩하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <XmlNamespaceMappingCollection x:Key="XmlNamespaceMappingCollectionKey"> <XmlNamespaceMapping Prefix="dc" Uri="http://purl.org/dc/elements/1.1/" /> </XmlNamespaceMappingCollection> <XmlDataProvider x:Key="XmlDataProviderKey" XmlNamespaceManager="{StaticResource XmlNamespaceMappingCollectionKey}" XPath="rss/channel/item" Source="https://icodebroker.tistory.com/rss" /> <DataTemplate x:Key="DataTemplateKey"> <Border BorderThickness="1" BorderBrush="Gray"> <Grid Height="50"> <Grid.RowDefinitions> <RowDefinition Height="25" /> <RowDefinition Height="25" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Text="{Binding XPath=title}" /> <TextBlock Grid.Row="1" Text="{Binding XPath=dc:date, FallbackValue=''}" /> </Grid> </Border> </DataTemplate> </Window.Resources> <ListBox Margin="10" Background="Honeydew" ItemTemplate="{StaticResource DataTemplateKey}" ItemsSource="{Binding Source={StaticResource XmlDataProviderKey}}" /> </Window> |
※ XmlDataProvider 엘리먼트의 Source 속성에 기존 설정된 URL이 없어지면서 본인
■ 마스터/상세 XML 데이터를 바인딩하는 방법을 보여준다. ▶ DATA\leagues.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<Leagues xmlns=""> <League name="League A"> <Division name="Division A"> <Team name="Team I" /> <Team name="Team II" /> <Team name="Team III" /> <Team name="Team IV" /> <Team name="Team V" /> </Division> <Division name="Division B"> <Team name="Team Blue" /> <Team name="Team Red" /> <Team name="Team Yellow" /> <Team name="Team Green" /> <Team name="Team Orange" /> </Division> <Division name="Division C"> <Team name="Team East" /> <Team name="Team West" /> <Team name="Team North" /> <Team name="Team South" /> </Division> </League> <League name="League B"> <Division name="Division A"> <Team name="Team 1" /> <Team name="Team 2" /> <Team name="Team 3" /> <Team name="Team 4" /> <Team name="Team 5" /> </Division> <Division name="Division B"> <Team name="Team Diamond" /> <Team name="Team Heart" /> <Team name="Team Club" /> <Team name="Team Spade" /> </Division> <Division name="Division C"> <Team name="Team Alpha" /> <Team name="Team Beta" /> <Team name="Team Gamma" /> <Team name="Team Delta" /> <Team name="Team Epsilon" /> </Division> </League> </Leagues> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <XmlDataProvider x:Key="XmlDataProviderKey" XPath="Leagues/League" Source="DATA\Leagues.xml" /> <DataTemplate x:Key="TextBlockTemplateKey"> <TextBlock Text="{Binding XPath=@name}" /> </DataTemplate> </Window.Resources> <Grid Margin="10" DataContext="{Binding Source={StaticResource XmlDataProviderKey}}"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0">My Soccer Leagues</Label> <ListBox Grid.Row="1" Grid.Column="0" IsSynchronizedWithCurrentItem="true" ItemTemplate="{StaticResource TextBlockTemplateKey}" ItemsSource="{Binding}" /> <Label Grid.Row="0" Grid.Column="2" Content="{Binding XPath=@name}" /> <ListBox Name="divisionListBox" Grid.Row="1" Grid.Column="2" IsSynchronizedWithCurrentItem="true" ItemTemplate="{StaticResource TextBlockTemplateKey}" ItemsSource="{Binding XPath=Division}" /> <Label Grid.Row="0" Grid.Column="4" Content="{Binding XPath=@name}" DataContext="{Binding ElementName=divisionListBox, Path=SelectedItem}" /> <ListBox Grid.Row="1" Grid.Column="4" DataContext="{Binding ElementName=divisionListBox, Path=SelectedItem}" ItemTemplate="{StaticResource TextBlockTemplateKey}" ItemsSource="{Binding XPath=Team}" /> </Grid> </Window> |
TestProject.zip
■ XmlDataProvider 엘리먼트의 XPath 속성을 사용해 XML 데이터를 사용하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <StackPanel.Resources> <XmlDataProvider x:Key="XmlDataProviderKey" XPath="Inventory/Books"> <x:XData> <Inventory xmlns=""> <Books> <Book ISBN="0-7356-0562-9" Stock="in" Number="9"> <Title>XML in Action</Title> <Summary>XML Web Technology</Summary> </Book> <Book ISBN="0-7356-1370-2" Stock="in" Number="8"> <Title>Programming Microsoft Windows With C#</Title> <Summary>C# Programming using the .NET Framework</Summary> </Book> <Book ISBN="0-7356-1288-9" Stock="out" Number="7"> <Title>Inside C#</Title> <Summary>C# Language Programming</Summary> </Book> <Book ISBN="0-7356-1377-X" Stock="in" Number="5"> <Title>Introducing Microsoft .NET</Title> <Summary>Overview of .NET Technology</Summary> </Book> <Book ISBN="0-7356-1448-2" Stock="out" Number="4"> <Title>Microsoft C# Language Specifications</Title> <Summary>The C# language definition</Summary> </Book> </Books> <CDs> <CD Stock="in" Number="3"> <Title>Classical Collection</Title> <Summary>Classical Music</Summary> </CD> <CD Stock="out" Number="9"> <Title>Jazz Collection</Title> <Summary>Jazz Music</Summary> </CD> </CDs> </Inventory> </x:XData> </XmlDataProvider> </StackPanel.Resources> <TextBlock HorizontalAlignment="Center" Margin="10" FontSize="20" FontWeight="Bold"> XML Data Source Sample </TextBlock> <ListBox Width="400" Height="300" Background="LightGray"> <ListBox.ItemsSource> <Binding XPath="*[@Stock='out'] | *[@Number>=8 or @Number=3]" Source="{StaticResource XmlDataProviderKey}" /> </ListBox.ItemsSource> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Foreground="Blue"> <TextBlock.Text> <Binding XPath="Title" /> </TextBlock.Text> </TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> </Window> |
TestProject.zip
■ XmlDocument 클래스의 WriteTo 메소드를 사용해 XML 문자열을 구하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region XML 구하기 - GetXML(document) /// <summary> /// XML 구하기 /// </summary> /// <param name="document">XML 문서</param> /// <returns>XML</returns> private static string GetXML(XmlDocument document) { using(StringWriter stringWriter = new StringWriter()) { using(XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter)) { document.WriteTo(xmlTextWriter); string xml = stringWriter.ToString(); return xml; } } } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { XmlDocument document = new XmlDocument(); document.Load("sample.xml"); string xml = GetXML(document); Console.WriteLine(xml); } #endregion } |
TestProject.zip
■ XmlDocument 클래스의 OuterXml 속성을 사용해 XML 문자열을 구하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { XmlDocument document = new XmlDocument(); document.Load("sample.xml"); Console.WriteLine(document.OuterXml); } #endregion } |
TestProject.zip
■ 도서 관리 프로그램을 만드는 방법을 보여준다. ▶ book.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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> |
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
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() |
TestProject.zip
■ Element 클래스의 text 속성을 사용해 해당 엘리먼트 텍스트를 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import xml.etree.ElementTree elementTree = xml.etree.ElementTree.parse("book.xml") elementIterator = elementTree.iter("book") for bookElement in elementIterator: titleElement = bookElement.find("title") title = titleElement.text isbn = bookElement.attrib["ISBN"] print("{0} [{1}]".format(title, isbn)) |
book.zip
■ Element 클래스의 attrib 속성을 사용해 특정 속성 값을 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import xml.etree.ElementTree elementTree = xml.etree.ElementTree.parse("book.xml") elementIterator = elementTree.iter("book") for bookElement in elementIterator: titleElement = bookElement.find("title") title = titleElement.text isbn = bookElement.attrib["ISBN"] print("{0} [{1}]".format(title, isbn)) |
book.zip
■ Element 클래스의 find 메소드를 사용해 특정 태그명이나 경로와 일치하는 엘리먼트를 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import xml.etree.ElementTree elementTree = xml.etree.ElementTree.parse("book.xml") elementIterator = elementTree.iter("book") for bookElement in elementIterator: titleElement = bookElement.find("title") title = titleElement.text isbn = bookElement.attrib["ISBN"] print("{0} [{1}]".format(title, isbn)) |
book.zip
■ ElementTree 클래스의 iter 메소드를 사용해 특정 태그 엘리먼트를 열거하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import xml.etree.ElementTree elementTree = xml.etree.ElementTree.parse("book.xml") elementIterator = elementTree.iter("book") for bookElement in elementIterator: titleElement = bookElement.find("title") title = titleElement.text isbn = bookElement.attrib["ISBN"] print("{0} [{1}]".format(title, isbn)) |
book.zip
■ Element 클래스의 appendChild 메소드를 사용해 자식 엘리먼트를 추가하는 방법을 보여준다. ▶ book.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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> |
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import xml.dom.minidom document = xml.dom.minidom.parse("book.xml") titleElement = document.createElement("title") titleText = document.createTextNode("파이썬 3.6 프로그래밍") titleElement.appendChild(titleText) bookElement = document.createElement("book") bookElement.setAttribute("ISBN", "979-11-5839-071-6") bookElement.appendChild(titleElement) booklistElement = document.firstChild booklistElement.appendChild(bookElement) lastBookElement = booklistElement.childNodes[booklistElement.childNodes.length - 1] print(lastBookElement.attributes["ISBN"].value) print(lastBookElement.childNodes[0].childNodes[0].data) """ 979-11-5839-071-6 파이썬 3.6 프로그래밍 """ |
TestProject.zip
■ XML 노드를 순회하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import xml.dom.minidom def GetNodeTypeName(nodeType): if nodeType == 1: return "ELEMENT" elif nodeType == 2: return "ATTRIBUTE" elif nodeType == 3: return "TEXT" elif nodeType == 4: return "CDATA SECTION" elif nodeType == 5: return "ENTITY" elif nodeType == 6: return "PROCESSING INSTRUCTION" elif nodeType == 7: return "COMMENT" elif nodeType == 8: return "DOCUMENT" elif nodeType == 9: return "DOCUMENT TYPE" else: return "NOTATION" def PrintNode(parentNode, level): if parentNode.nodeType == 3: return if level == 0: indent = "" else: indent = " " * level * 4 print("{0}{1} ({2})".format(indent, parentNode.nodeName, GetNodeTypeName(parentNode.nodeType))) for childNode in parentNode.childNodes: if childNode.nodeType == 3: continue PrintNode(childNode, level + 1) document = xml.dom.minidom.parse("book.xml") for childNode in document.childNodes: PrintNode(childNode, 0) |
book.zip
■ parse 함수를 사용해 XML 파일을 로드하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import xml.dom.minidom document = xml.dom.minidom.parse("book.xml") print(document.toxml()) """ <?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> """ |
book.zip
■ Document 클래스의 getElementsByTagName 메소드를 사용해 태그명에 일치하는 엘리먼트 리스트를 구하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import xml.dom.minidom xmlString = """ <item> <name>test</name> </item> """ document = xml.dom.minidom.parseString(xmlString) nodeList = document.getElementsByTagName("name") print(nodeList) """ [<DOM Element: name at 0x1aca41136d0>] """ |
■ parseString 함수를 사용해 XML 문자열을 파싱하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import xml.dom.minidom xmlString = """ <item> <name>test</name> </item> """ document = xml.dom.minidom.parseString(xmlString) print(document.toxml()) """ <?xml version="1.0" ?><item> <name>test</name> </item> """ |
■ xmlparser 클래스를 사용해 XML 문자열을 파싱하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import xml.parsers.expat def ProcessStartElement(name, attributeDictionary): print("시작 엘리먼트 : ", name, attributeDictionary) def ProcessCharacterData(data): print("문자 데이터 : ", repr(data)) xmlParser = xml.parsers.expat.ParserCreate() xmlParser.StartElementHandler = ProcessStartElement xmlParser.CharacterDataHandler = ProcessCharacterData xmlParser.Parse("""<?xml version="1.0"?><book ISBN="1111"><title>Loving Python</title></book>""") """ Start element : book {'ISBN': '1111'} Start element : title {} Character data : 'Loving Python' """ |
■ XmlDocument 클래스의 Load 메소드를 사용해 XML 파일을 로드하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { XmlDocument document = new XmlDocument(); document.Load("sample.xml"); XmlNode node = document.DocumentElement.SelectSingleNode("/UserInfo/User"); foreach(XmlNode childNode in node.ChildNodes) { Console.WriteLine(childNode.InnerText); } } #endregion } |
TestProject.zip
■ XmlDocument 클래스의 LoadXml 메소드를 사용해 XML 문자열을 로드하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string xml = @" <UserInfo> <User userno=""1""> <UserID>admin</UserID> <Password>Uaps+82i8GTmJBZbvbkI6Q==</Password> <UserType>Administrator</UserType> </User> <User userno=""2""> <UserID>dexter</UserID> <Password>Uaps+82i8GTmJBZbvbkI6Q==</Password> <UserType>Administrator</UserType> </User> <User userno=""3""> <UserID>sunny</UserID> <Password>Uaps+82i8GTmJBZbvbkI6Q==</Password> <UserType>Operator</UserType> </User> <User userno=""4""> <UserID>john</UserID> <Password>Uaps+82i8GTmJBZbvbkI6Q==</Password> <UserType>Visitor</UserType> </User> </UserInfo> "; XmlDocument document = new XmlDocument(); document.LoadXml(xml); XmlNode node = document.DocumentElement.SelectSingleNode("/UserInfo/User"); foreach(XmlNode childNode in node.ChildNodes) { Console.WriteLine(childNode.InnerText); } } #endregion } |
TestProject.zip
■ XmlNode 클래스의 Attributes 속성을 사용해 XML 노드 특성 값을 구하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { XmlDocument document = new XmlDocument(); document.Load("sample.xml"); XmlNode node = document.DocumentElement.SelectSingleNode("/UserInfo"); foreach(XmlNode childNode in node.ChildNodes) { Console.WriteLine(childNode.Attributes["userno"].InnerText); } } #endregion } |
TestProject.zip
■ XmlElement 클래스의 SelectSingleNode 메소드를 사용해 단일 노드를 선택하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
using System.Xml; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { XmlDocument document = new XmlDocument(); document.Load("sample.xml"); XmlElement element = document.DocumentElement; XmlNode node = element.SelectSingleNode("/UserInfo/User"); foreach(XmlNode childNode in node.ChildNodes) { Console.WriteLine(childNode.InnerText); } } #endregion } |
TestProject.zip
■ XmlWriter 클래스를 사용해 XML 포맷을 정규화하는 방법을 보여준다. ▶ XmlWriter 클래스 : XML 포맷 정규화하기 예제 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 |
string xml = "<?xml version=\"1.0\"?><response><error code=\"1\"> Success</error></response>"; Console.WriteLine(NormalizeXMLFormat(xml)); /* <?xml version="1.0" encoding="utf-16"?> <response> <error code="1"> Success</error> </response> */ |
▶ XmlWriter 클래스