시작하기
XML 문서 구조
XML 문서는 XML 선언으로 시작합니다. 요소는 올바르게 중첩되고 닫혀야 합니다. 속성은 추가 메타데이터를 제공합니다. xmlns는 이름 충돌을 피하기 위해 XML 네임스페이스를 선언합니다.
<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment -->
<bookstore xmlns="https://example.com/books">
<book id="b1" category="fiction">
<title lang="en">The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price currency="USD">12.99</price>
</book>
<book id="b2" category="programming">
<title lang="en">XML Guide</title>
<author>John Doe</author>
<price currency="USD">29.99</price>
</book>
</bookstore>XML 선언
XML 선언은 프롤로그의 첫 줄입니다. 'version'은 필수(1.0 또는 1.1)입니다. 'encoding'의 기본값은 UTF-8입니다. 'standalone'은 외부 DTD 선언이 필요한지 파서에 알려줍니다.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- version is required; encoding and standalone are optional -->
<!-- encoding defaults to UTF-8 -->
<!-- standalone="yes" means no external markup declarations -->
<root>
<child>text</child>
</root>주석과 처리 명령
주석은 <!-- -->를 쓰며 중첩될 수 없고 안에 '--'를 포함할 수 없습니다. xml-stylesheet 같은 처리 명령(PI)은 앱별 정보를 파서에 전달합니다. PI는 <?target data?>를 씁니다.
<?xml version="1.0"?>
<!-- a comment: ignored by the parser, cannot contain -- -->
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<root>
<!-- comments can span
multiple lines -->
<item>data</item>
</root>잘 형성된 XML
잘 형성됨(well-formed)은 루트 요소 하나, 올바른 중첩, 모든 태그 닫힘, 속성 따옴표, 중복 속성 없음을 뜻합니다. 문서는 파싱 가능하려면 반드시 잘 형성되어야 하며, DTD/Schema에 대한 유효성은 선택입니다.
<!-- WELL-FORMED: single root, properly nested, closed -->
<root>
<a>
<b>text</b>
</a>
</root>
<!-- NOT well-formed: two roots, overlapping tags -->
<!-- <a><b></a></b> -->
<!-- <x></x><y></y> (no single root) -->
<!-- All attributes must be quoted -->
<item id='1' type="x"/>XML 프롤로그와 공백
프롤로그는 XML 선언과 선택적 DOCTYPE을 포함합니다. xml:space='preserve'는 공백을 유지하라고 파서에 알리고 'default'는 일반 처리를 허용합니다. 요소 사이 공백은 대체로 중요하지 않습니다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root SYSTEM "root.dtd">
<root xml:space="preserve">
<item> spaced text </item>
<item xml:space="default"> trimmed </item>
</root>CDATA 개요
CDATA 섹션은 파서가 마크업으로 해석하지 않아야 하는 텍스트를 표시합니다. CDATA 안에서는 <, >, & 같은 문자를 이스케이프할 필요가 없습니다. CDATA는 중첩될 수 없고 리터럴 ']]>'을 포함할 수 없습니다.
<?xml version="1.0"?>
<root>
<code><![CDATA[
if (a < b && c > d) {
console.log("no escaping needed: < > & ");
}
]]></code>
</root>요소와 속성
요소 vs 속성
속성은 메타데이터(id, 타입, 플래그)에, 요소는 구조나 반복 값이 있는 데이터에 적합합니다. 속성은 요소당 한 번 나타나며 중첩 구조를 담을 수 없습니다. 엄격한 규칙은 없고 일관성이 가장 중요합니다.
<!-- Attributes: metadata/identifiers; Elements: data -->
<person id="p1">
<name>Alice</name>
<age>30</age>
</person>
<!-- vs. putting everything in attributes -->
<person id="p1" name="Alice" age="30"/>
<!-- Rule of thumb: use elements for data you display,
attributes for IDs, types, and metadata -->빈 요소
빈 요소에는 내용이 없습니다. 자기 닫힘 형식 <tag/>는 <tag></tag>의 단축입니다. '/>' 앞의 공백은 가독성과 XHTML 호환성을 위한 스타일 관례입니다.
<!-- Three equivalent empty-element forms -->
<br></br>
<br/>
<br />
<!-- empty element with attributes -->
<img src="logo.png" alt="Logo" width="200" height="100"/>
<!-- self-closing with namespace -->
<xlink:link xmlns:xlink="http://www.w3.org/1999/xlink" href="#sec1"/>중첩 요소
요소는 계층적으로 중첩되며 역순으로 닫혀야 하고 겹칠 수 없습니다. 중첩은 구조를 표현합니다. 깊게 중첩된 트리는 유효하지만 가독성과 파싱 성능을 해칠 수 있습니다.
<library>
<section name="fiction">
<book>
<title>Book A</title>
<authors>
<author>Author 1</author>
<author>Author 2</author>
</authors>
</book>
</section>
</library>
<!-- WRONG: tags must not overlap -->
<!-- <a><b></a></b> -->속성 값과 따옴표
속성 값은 작은따옴표나 큰따옴표로 감싸야 합니다. 큰따옴표로 감싼 값 안의 큰따옴표는 "로 이스케이프해야 합니다. 속성은 요소당 한 번만 나타날 수 있으므로 반복 값에는 자 식 요소를 사용하세요.
<!-- Both single and double quotes are allowed -->
<item id="q1" name='quick'/>
<msg text="He said "hi""/>
<msg text='She said 'hi''/>
<!-- attribute values MUST be quoted -->
<!-- <item id=q1/> is NOT well-formed -->
<!-- an attribute can appear at most once per element -->
<point x="1" y="2" z="3"/>기본 및 고정 속성
DTD 속성 선언은 #REQUIRED(반드시 나타남), #IMPLIED(선택), #FIXED(상수 값), 리터럴 기본값을 지원합니다. #FIXED 속성은 항상 선언된 값과 같아야 하며 그렇지 않으면 문서가 유효하지 않습니다.
<!-- In a DTD, attributes can have defaults -->
<!ATTLIST item
type CDATA "standard"
status CDATA #REQUIRED
version CDATA #FIXED "1.0"
note CDATA #IMPLIED>
<item status="active"/>
<!-- 'type' defaults to "standard", 'version' is fixed,
'note' is optional (#IMPLIED) -->요소 이름 규칙
요소 이름은 문자나 밑줄로 시작하고 문자, 숫자, 하이픈, 밑줄, 점을 포함할 수 있습니다. 이름은 'xml'(대소문자 무관)로 시작할 수 없습니다. XML은 대소문자를 구분하므로 <Tag>와 <tag>는 다릅니다.
<!-- Names: start with a letter or underscore,
continue with letters, digits, hyphens, underscores, dots -->
<my-element>ok</my-element>
<my.element>ok</my.element>
<my_element>ok</my_element>
<_private>ok</_private>
<x-1>ok</x-1>
<!-- NOT allowed: starting with a digit or 'xml', containing spaces -->
<!-- <2way/> -->
<!-- <my element/> -->
<!-- <XmlTag/> (names are case-sensitive; 'xml' prefix is reserved) -->네임스페이스
기본 네임스페이스
기본 네임스페이스(xmlns=URI)는 선언된 요소와 접두사 없는 모든 하위 요소에 적용됩니다. 덮어쓰지 않는 한 자식 요소가 상속합니다. 속성은 기본 네임스페이스를 절대 사용하지 않습니다.
<?xml version="1.0"?>
<table xmlns="http://www.w3.org/1999/xhtml">
<tr>
<td>Cell content</td>
<td>More content</td>
</tr>
</table>
<!-- All elements without a prefix use the default namespace -->네임스페이스 접두사
네임스페 이스 접두사는 xmlns:prefix=URI로 선언하고 prefix:element로 사용합니다. 접두사는 별칭일 뿐이며 항등성에는 URI만 중요합니다. 접두사는 대소문자를 구분합니다.
<?xml version="1.0"?>
<root xmlns:bk="https://example.com/books"
xmlns:au="https://example.com/authors">
<bk:book bk:id="b1">
<au:author au:name="Jane Doe"/>
<bk:title>XML Guide</bk:title>
</bk:book>
</root>여러 네임스페이스
한 문서에 여러 네임스페이스를 섞을 수 있습니다. 각 접두사를 (보통 루트에) 한 번 선언하고 재사용하세요. 요소에 네임스페이스를 선언하면 그 요소와 하위 요소에 적용됩니다.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<m:GetPrice xsi:type="xsd:string"
xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>네임스페이스 범위
네임스페이스 선언은 선언된 요소와 하위 요소로 범위가 제한됩니다. 자식 안에서 재선언하면 그 하위 트리에 대해 부모의 접두사 매핑을 덮어씁니다. 자식이 닫히면 원래 매핑이 복원됩니다.
<?xml version="1.0"?>
<root xmlns:a="http://a.example">
<a:item>A</a:item>
<child xmlns:a="http://b.example">
<!-- here 'a' is REBOUND to the b.example URI -->
<a:item>B</a:item>
</child>
<!-- outside child, 'a' is back to a.example -->
<a:item>A again</a:item>
</root>흔한 네임스페이스
이 URI들은 잘 알려진 식별자이며 가져와야 하는 URL이 아닙니다. xsi 네임스페이스는 스키마 인스턴스 속성(type, nil, schemaLocation)을 제공합니다. XSD, XSL, SVG, SOAP, Atom, Dublin Core(dc)에는 각각 표준 URI가 있습니다.
<!-- Frequently used namespace URIs -->
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"
xmlns:svg = "http://www.w3.org/2000/svg"
xmlns:html = "http://www.w3.org/1999/xhtml"
xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:atom = "http://www.w3.org/2005/Atom"
xmlns:dc = "http://purl.org/dc/elements/1.1/"XSD의 대상 네임스페이스
스키마의 targetNamespace는 정의하는 요소의 네임스페이스입니다. elementFormDefault='qualified'는 로컬 선언 요소가 대상 네임스페이스에 속함을 뜻합니다. tns 접두사는 '이 네임스페이스'를 위한 관례입니다.
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/orders"
xmlns:tns="https://example.com/orders"
elementFormDefault="qualified">
<xs:element name="order" type="tns:OrderType"/>
<xs:complexType name="OrderType">
<xs:sequence>
<xs:element name="item" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>CDATA와 엔티티
미리 정의된 엔티티
XML은 다섯 엔티티를 미리 정의합니다: < (<), > (>), & (&), ' ('), " ("). &는 항상 이스케이프해야 하고(CDATA 없는 텍스트에서도), <는 태그 시작이 아닌 경우 이스케이프해야 하며, 따옴표는 주로 속성에서 중요합니다.
<?xml version="1.0"?>
<root>
<lt>less than: <</lt>
<gt>greater than: ></gt>
<amp>ampersand: &</amp>
<apos>apostrophe: '</apos>
<quot>quote: "</quot>
<!-- < > & ' " are the 5 built-in entities -->
</root>문자 참조
문자 참조는 유니코드 코드 포인트를 사용합니다. ©는 ©(10진) 또는 ©(16진)입니다. 요소 텍스트와 속성 값에서 동작하고 인코딩의 영향을 받지 않습니다. 모든 유니코드 문자를 표현할 수 있습니다.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<decimal>© 2024 Company</decimal>
<hex>© 2024 Company</hex>
<euro>Price: €10</euro>
<emoji>Smile: 😀</emoji>
</root>
<!-- &#NNN; decimal code point -->
<!-- &#xHHH; hexadecimal code point -->CDATA 섹션
CDATA 섹션은 <, >, &를 이스케이프 없이 포함하게 하므로 코드와 마크업에 유용합니다. CDATA는 ']]>'를 리터럴로 포함할 수 없으므로 예제처럼 섹션을 나누어 삽입하세요. CDATA는 요소로 파싱되지 않는 문자 데이터입니다.
<?xml version="1.0"?>
<root>
<script><![CDATA[
function check(a, b) {
if (a < b && b > 0) {
return a & b;
}
}
]]></script>
<!-- to include ]]> inside CDATA, split it -->
<data><![CDATA[foo]]]]><![CDATA[>bar]]></data>
</root>사용자 정의 엔티티(DTD)
내부 엔티티는 DTD에서 선언되고 참조된 곳에서 확장됩니다. 텍스트 매크로처럼 동작하고 다른 엔티티를 참조할 수 있습니다. 반복 상용구에 유용합니다. 주의: 외부/일반 엔티티는 XXE 보안 위험이 될 수 있습니다.
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY company "Acme Corp.">
<!ENTITY version "2.0">
<!ENTITY copyright "Copyright © 2024 &company;">
]>
<root>
<product>&company; Toolkit v&version;</product>
<footer>©right;</footer>
</root>
<!-- Entities are expanded during parsing -->속성에서 이스케이프
속성 값 안에서는 &를 &로 이스케이프하고 값을 구분하는 따옴표(" 또는 ')도 이스케이프해야 합니다. <도 이스케이프하는 것이 좋습니다. 속성의 줄바꿈과 탭은 파서가 공백으로 정규화합니다.
<?xml version="1.0"?>
<root>
<link url="https://example.com?a=1&b=2"/>
<msg text="Say "hello" & smile"/>
<path value='C:\Users\name'/>
<data value="<tagged>"/>
</root>매개변수 엔티티
매개변수 엔티티(%로 선언)는 DTD 안에서만 사용해 재사용 가능한 콘텐츠 모델을 만듭니다. %name;(세미콜론 포함)으로 참조합니다. 일반 엔티티(&name;)는 문서 콘텐츠에서 사용합니다.
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY % inline " (#PCDATA | em | strong)* ">
<!ELEMENT p %inline;>
<!ELEMENT em %inline;>
<!ELEMENT strong %inline;>
<!ELEMENT root (p)*>
]>
<root>
<p>Hello <em>world</em> and <strong>XML</strong>.</p>
</root>DTD(문서 타입 정의)
내부 DTD
내부 DTD는 DOCTYPE 안의 대괄호에 인라인 선언합니다. 어떤 요소가 존재하는지, 콘텐 츠 모델과 속성을 정의합니다. 내부 DTD는 자기 완결적이지만 그 문서 하나에만 적용됩니다.
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Alice</to>
<from>Bob</from>
<heading>Reminder</heading>
<body>Don't forget the meeting</body>
</note>외부 DTD
외부 DTD는 SYSTEM(비공개) 또는 PUBLIC(공개 식별자 + URI)으로 참조하는 별도 .dtd 파일에 있습니다. 외부 DTD로 많은 문서가 하나의 정의를 공유합니다. SYSTEM 'file.dtd'가 가장 흔한 형식입니다.
<!-- File: note.dtd -->
<!ELEMENT note (to, from, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!-- File: note.xml -->
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Alice</to>
<from>Bob</from>
<body>Hello</body>
</note>요소 선언
콘텐츠 모델은 ,(순서), |(선택), ?(0-1), *(0+), +(1+)를 씁니다. #PCDATA는 텍스트이고 혼합 콘텐츠는 요소와 텍스트가 섞이는 것을 허용합니다. EMPTY는 내용 없음, ANY는 검사를 비활성화합니다(운영에서는 피하세요).
<!ELEMENT root (child1, child2*)>
<!-- content model operators -->
<!ELEMENT list (item+)> <!-- one or more item -->
<!ELEMENT opt (item?)> <!-- zero or one item -->
<!ELEMENT any (item1 | item2)*> <!-- choice, any number -->
<!ELEMENT text (#PCDATA)> <!-- parsed character data -->
<!ELEMENT mixed (#PCDATA | em)*> <!-- mixed content -->
<!ELEMENT empty EMPTY> <!-- no content -->
<!ELEMENT any ANY> <!-- any content -->속성 선언
ATTLIST는 속성의 타입과 기본값을 선언합니다. ID는 고유 식별자이고 IDREF/IDREFS는 ID를 참조합니다(상호 링크). NMTOKEN은 이름 토큰입니다. 열거형 타입은 허용 값을 나열합니다. 기본값: #REQUIRED, #IMPLIED, #FIXED, 리터럴.
<!ATTLIST book
id ID #REQUIRED
category CDATA #IMPLIED
lang NMTOKEN "en"
status (draft|final) "draft"
version CDATA #FIXED "1.0">
<!-- Types: CDATA, ID, IDREF, IDREFS, NMTOKEN, NMTOKENS,
NOTATION, enumerated (a|b|c) -->
<!ATTLIST link ref IDREF #REQUIRED>엔티티 선언
일반 엔티티(&name;)는 콘텐츠에서 확장되고 매개변수 엔티티(%name;)는 DTD에서 확장됩니다. 외부 파싱 엔티티는 다른 XML을 포함하고, 비파싱 엔티티(NDATA 포함)는 NOTATION으로 참조되는 비XML 데이터를 가리킵니다. 외부 엔티티는 XXE 인젝션을 일으킬 수 있습니다.
<!DOCTYPE root [
<!-- internal general entity -->
<!ENTITY name "Alice">
<!-- external parsed entity -->
<!ENTITY chap1 SYSTEM "chapter1.xml">
<!-- unparsed entity (binary, e.g. image) -->
<!ENTITY logo SYSTEM "logo.png" NDATA image>
<!-- notation declaration for unparsed entities -->
<!NOTATION image SYSTEM "image/png">
<!-- parameter entity (DTD-only) -->
<!ENTITY % block "(p | list)+">
]>
<root>&name;</root>DTD 검증
검증은 문서가 DTD(요소 순서, 허용 속성, ID 고유성)와 일치하는지 확인합니다. minidom 같은 표준 DOM 파서는 기본적으로 검증하지 않으므로 lxml(Python), xmllint(명령줄), 검증 파서를 사용하세요.
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "schema.dtd">
<root>
<item id="x1">valid</item>
</root>
<!-- Validate with Python: -->
<!-- import xml.dom.minidom as m
dom = m.parse("file.xml")
# minidom does NOT validate; use lxml: -->
<!-- from lxml import etree
dtd = etree.DTD("schema.dtd")
tree = etree.parse("file.xml")
print(dtd.validate(tree)) -->XML 스키마(XSD)
스키마 구조
XSD 자체가 XML 문서입니다. 루트 <schema>는 XSD 네임스페이스와 정의하는 요소의 대상 네임스페이스를 선언합니다. elementFormDefault='qualified'는 로컬 요소를 대상 네임스페이스에 둡니다.
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/order"
xmlns:tns="https://example.com/order"
elementFormDefault="qualified">
<xs:element name="order" type="tns:OrderType"/>
<xs:complexType name="OrderType">
<xs:sequence>
<xs:element name="customer" type="xs:string"/>
<xs:element name="total" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>
</xs:schema>단순 타입
simpleType은 패싯(pattern, minInclusive, enumeration, length 등)으로 기본 타입을 제한합니다. 단순 타입은 텍스트 콘텐츠와 속성만 가지며 자식 요소가 없습니다. 스키마 전체에서 재사용할 수 있습니다.
<xs:simpleType name="emailType">
<xs:restriction base="xs:string">
<xs:pattern value="[^@]+@[^@]+.[^@]+"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ageType">
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="email" type="tns:emailType"/>
<xs:element name="age" type="tns:ageType"/>복합 타입
complexType은 자식 요소와 속성을 담을 수 있습니다. sequence는 순서를 강제하고 choice는 여러 개 중 하나를, all은 임의 순서(각각 최대 한 번)를 허용합니다. 컴포지터를 중첩해 풍부한 구조를 표현할 수 있습니다.
<xs:complexType name="AddressType">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
</xs:sequence>
<xs:attribute name="country" type="xs:string" default="US"/>
</xs:complexType>
<!-- Content model indicators: sequence, choice, all -->
<xs:complexType name="ContactType">
<xs:choice>
<xs:element name="phone" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:choice>
</xs:complexType>내장 타입
XSD는 풍부한 타입 계층을 제공합니다: 문자열, 숫자(integer, decimal, float), 날짜/시간, 불리언, anyURI, ID/IDREF, QName. 각각 length, pattern, enumeration 같은 패싯으로 추가 제한할 수 있습니다.
<!-- Common XSD built-in types -->
<xs:element name="count" type="xs:integer"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="flag" type="xs:boolean"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="date" type="xs:date"/> <!-- 2024-01-15 -->
<xs:element name="time" type="xs:time"/> <!-- 13:45:00 -->
<xs:element name="dt" type="xs:dateTime"/> <!-- 2024-01-15T13:45:00 -->
<xs:element name="id" type="xs:ID"/>
<xs:element name="ref" type="xs:IDREF"/>
<xs:element name="uri" type="xs:anyURI"/>제한(패싯)
패싯은 단순 타입을 제약합니다: enumeration(허용 값), pattern(정규식), length/minLength/maxLength, min/maxInclusive/Exclusive, totalDigits, fractionDigits, whiteSpace(preserve/replace/collapse).
<xs:simpleType name="ColorType">
<xs:restriction base="xs:string">
<xs:enumeration value="red"/>
<xs:enumeration value="green"/>
<xs:enumeration value="blue"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PasswordType">
<xs:restriction base="xs:string">
<xs:minLength value="8"/>
<xs:maxLength value="32"/>
<xs:pattern value="[A-Za-z0-9!@#]+"/>
</xs:restriction>
</xs:simpleType>XSD의 요소와 속성
minOccurs/maxOccurs는 카디널리티를 제어합니다(기본 1). maxOccurs='unbounded'는 임의 개수를 허용합니다. 속성 'use'는 required/optional/prohibited이고 선택적 default나 fixed 값을 가집니다. 익명 복합 타입은 정의를 인라인합니다.
<xs:element name="product">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"
minOccurs="1" maxOccurs="1"/>
<xs:element name="tag" type="xs:string"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="sku" type="xs:string" use="required"/>
<xs:attribute name="weight" type="xs:decimal" use="optional"
default="0.0"/>
</xs:complexType>
</xs:element>XPath
경로 표현식
XPath는 경로 유사 표현식을 씁니다. '/'는 루트에서 선택하고 '//'는 임의 깊이의 하위를 선택합니다. '*'는 모든 요소의 와일드카드이고 '@'는 속성을 선택합니다. '/'로 시작하는 표현식은 절대 경로입니다.
<!-- Sample: <bookstore><book><title>..</title></book></bookstore> -->
/bookstore/book/title <!-- absolute path -->
bookstore/book/title <!-- relative path -->
//title <!-- any title, anywhere -->
/bookstore//title <!-- title anywhere under bookstore -->
bookstore/* <!-- all children of bookstore -->
//@lang <!-- all lang attributes -->
//@* <!-- all attributes -->조건자
[ ] 안의 조건자는 노드 집합을 필터링합니다. 인덱싱은 1부터 시작합니다. last()와 position()은 문맥에서 노드 위치를 가리킵니다. 조건자는 요소 텍스트, 속성(@name), 계산 값을 검사할 수 있습니다.
//book[1] <!-- first book -->
//book[last()] <!-- last book -->
//book[position() <= 3] <!-- first three books -->
//book[price > 25] <!-- books with price > 25 -->
//book[@category='web'] <!-- books in the web category -->
//book[author='Smith'] <!-- books authored by Smith -->
//book[@lang][2] <!-- 2nd book that has a lang attr -->축
축은 탐색 방향을 정의합니다: child(기본), descendant, parent(..), ancestor, following-sibling, preceding-sibling, attribute(@), self(.), descendant-or-self(//). 대부분 실무에서 쓰는 단축 형식이 있습니다.
child::book <!-- default axis: children named book -->
descendant::title <!-- all title descendants -->
parent::* <!-- the parent element (shorthand: ..) -->
ancestor::section <!-- all section ancestors -->
following-sibling::p <!-- p elements after this one -->
preceding::item <!-- items before this in document order -->
attribute::id <!-- the id attribute (shorthand: @id) -->
self::node() <!-- the current node (shorthand: .) -->함수
XPath 1.0에는 내장 함수가 있습니다: count, sum, string-length, contains, starts-with, normalize-space, name, concat, substring, round 등. XPath 2.0+는 함수 라이브러리를 크게 확장하고 타입을 추가합니다.
count(//book) <!-- number of book elements -->
string-length(//title) <!-- length of first title's text -->
contains(//name, 'Ali') <!-- true if name contains 'Ali' -->
starts-with(@id, 'b') <!-- true if id starts with 'b' -->
normalize-space(//summary) <!-- collapse whitespace -->
name(//*[1]) <!-- name of the first element -->
concat(/a, /b) <!-- concatenate strings -->
sum(//price) <!-- sum of all price values -->연산자
XPath는 동등 비교에 =(==가 아닌 단일 =)를 쓰고 논리에 'and'/'or'(&& / || 아님)를 씁니다. '/'는 경로용으로 예약되어 있어 나눗셈은 'div', 나머지는 'mod'입니다. '|'는 노드 집합의 합집합을 계산합니다.
<!-- Comparison: =, !=, <, >, <=, >= -->
//book[price = 29.99]
//book[price < 20]
<!-- Logical: and, or -->
//book[price > 10 and price < 30]
//book[@cat='a' or @cat='b']
<!-- Arithmetic: + - * div mod -->
//item[price * quantity > 100]
5 div 2 <!-- 2.5 -->
5 mod 2 <!-- 1 -->
<!-- Union: | -->
//book | //magazineXPath 예제
이 패턴들은 경로, 조건자, 함수를 결합해 실제 쿼리를 만듭니다. text()는 텍스트 노드를 선택하고 min()은 XPath 2.0+가 필요합니다. 조건자가 있는 //* 와일드카드는 전체 트리에서 속성으로 요소를 찾는 흔한 방법입니다.
<!-- Select all book titles priced over 20 -->
//book[price > 20]/title/text()
<!-- The category of the cheapest book -->
//book[price = min(//book/price)]/@category
<!-- Authors of books in the 'programming' category -->
//book[@category='programming']/author
<!-- Every 2nd item in each list -->
//list/item[position() mod 2 = 0]
<!-- Elements with a specific attribute value -->
//*[@lang='fr']XSLT 변환
기본 변환
XSLT 스타일시트는 XML입니다. 템플릿은 XPath로 노드를 일치시키고 apply-templates는 선택한 노드를 재귀 처리합니다. value-of는 텍스트를 추출합니다. match='/' 템플릿이 문서 루트에서 먼저 실행됩니다.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Book List</h2>
<xsl:apply-templates select="bookstore/book"/>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<p><xsl:value-of select="title"/> - <xsl:value-of select="price"/></p>
</xsl:template>
</xsl:stylesheet>xsl:template과 apply-templates
match 템플릿은 프로세서가 일치 노드를 방문할 때 발생하고 이름 있는 템플릿은 call-template으로 명시 호출합니다. select 없는 apply-templates는 모든 자식을 처리해 재귀적 규칙 기반 변환을 가능하게 합니다.
<xsl:template match="book">
<div class="book">
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="author"/>
</div>
</xsl:template>
<xsl:template match="title">
<h3><xsl:apply-templates/></h3>
</xsl:template>
<!-- named template (like a function) -->
<xsl:template name="divider">
<hr/>
</xsl:template>xsl:value-of와 xsl:for-each
xsl:for-each는 노드 집합을 반복하며 문맥 노드를 바꿉니다. 평면 출력에는 템플릿보다 간단한 경우가 많지만 과도하게 쓰면 스타일시트가 절차적으로 됩니다. 재귀 구조에는 템플릿과 apply-templates를 선호하세요.
<xsl:template match="/">
<ul>
<xsl:for-each select="bookstore/book">
<li>
<xsl:value-of select="title"/>
(<xsl:value-of select="@category"/>)
</li>
</xsl:for-each>
</ul>
</xsl:template>
<!-- value-of outputs the string value of an expression -->xsl:if와 xsl:choose
xsl:if에는 else가 없으므로 다중 분기에는 xsl:choose를 사용하세요. 'test' 표현식은 XPath 불리언 규칙을 따릅니다. 비어 있지 않은 노드 집합은 참, 빈 집합은 거짓, 0이 아닌 숫자는 참입니다.
<xsl:for-each select="bookstore/book">
<xsl:if test="price > 25">
<premium><xsl:value-of select="title"/></premium>
</xsl:if>
<xsl:choose>
<xsl:when test="@category='fiction'">F</xsl:when>
<xsl:when test="@category='programming'">P</xsl:when>
<xsl:otherwise>?</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
<!-- test uses XPath; non-empty node-sets and non-zero numbers are true -->xsl:sort와 xsl:variable
xsl:sort는 현재 노드 집합을 하나 이상의 키로 재정렬하며 data-type은 'text' 또는 'number'입니다. 변수(xsl:variable)는 불변이고 범위가 있습니다. 스타일시트 XML의 속성 값에서 <를 <로 이스케이프하는 것을 잊지 마세요.
<xsl:variable name="max-price" select="50"/>
<xsl:for-each select="bookstore/book[price < $max-price]">
<xsl:sort select="price" data-type="number" order="descending"/>
<xsl:sort select="title" order="ascending"/>
<p>
<xsl:value-of select="title"/>: <xsl:value-of select="price"/>
</p>
</xsl:for-each>
<!-- Note: in XSLT, < must be written < inside test attributes -->xsl:apply-templates와 모드
모드는 같은 소스 노드 집합을 다른 방식(예: 목차 vs 전체 항목)으로 처리하게 합니다. template과 apply-templates의 mode 속성이 일치해야 합니다. 모드가 없으면 모드 없는 템플릿만 적용됩니다.
<!-- A template can have a 'mode' for different outputs -->
<xsl:template match="book" mode="list">
<li><xsl:value-of select="title"/></li>
</xsl:template>
<xsl:template match="book" mode="detail">
<div><h3><xsl:value-of select="title"/></h3>
<p><xsl:value-of select="author"/></p></div>
</xsl:template>
<!-- Invoke a specific mode -->
<xsl:apply-templates select="bookstore/book" mode="list"/>
<xsl:apply-templates select="bookstore/book" mode="detail"/>XQuery
FLWOR 표현식
FLWOR은 XQuery의 핵심 구성입니다. for는 변수를 시퀀스 항목에 바인딩하고 let은 계산 값을 바인딩하며 where는 필터링하고 order by는 정렬하며 return은 출력을 만듭니다. SQL의 SELECT-FROM-WHERE와 비슷합니다.
for $b in /bookstore/book
let $discount := $b/price * 0.9
where $b/price > 20
order by $b/price descending
return
<book>
<title>{ $b/title/text() }</title>
<salePrice>{ $discount }</salePrice>
</book>
<!-- FLWOR = For, Let, Where, Order by, Return -->경로 표현식
XQuery는 XPath를 직접 포함합니다. doc('file.xml')은 문서를 로드하고 collection('uri')는 여러 문서를 질의합니다. 경로 표현식은 노드 시퀀스를 반환하며 FLWOR이 이를 반복할 수 있습니다.
(: XQuery uses XPath for navigation :)
/bookstore/book/title/text()
/bookstore/book[@category='web']
//author[contains(., 'Smith')]
(: Use doc() to open an external document :)
doc('catalog.xml')//book[price < 30]
(: collection() queries a set of documents :)
collection('/db/books')//title조건자와 조인
여러 'for' 절이 조인(SQL JOIN 같은)을 이룹니다. XQuery는 조합을 반복하고 where로 필터링해 조인합니다. 큰 데이터셋에는 중첩 루프보다 조건자나 키를 통한 명시적 조인이 효율적입니다.
(: Join books to authors by id :)
for $b in doc('books.xml')//book
for $a in doc('authors.xml')//author
where $b/@author-id = $a/@id
return
<entry>
<title>{ $b/title/text() }</title>
<author>{ $a/name/text() }</author>
</entry>
(: Equivalent join with a predicate :)
for $b in doc('books.xml')//book
return
<entry>{ $b/title, $b/@author-id }</entry>조건문과 수량 표현
XQuery에는 if-then-else(else 필수), 수량 표현(some/every ... satisfies), 노드 타입 분기를 위한 typeswitch가 있습니다. 조건은 XPath 스타일 불리언 의미를 따릅니다.
(: if-then-else :)
for $b in //book
return
if ($b/price > 30) then <expensive>{ $b/title }</expensive>
else <cheap>{ $b/title }</cheap>
(: quantified expressions :)
some $a in //author satisfies contains($a, 'Smith')
every $p in //price satisfies $p > 0
(: typeswitch for type-based dispatch :)
typeswitch($node)
case element(book) return "book"
case element(author) return "author"
default return "other"함수
XQuery는 XPath 함수를 재사용하고 string-join, distinct-values, avg, min, max 등 많은 함수를 추가합니다. 사용자 함수는 모듈에 매개변수와 반환 타입과 함께 선언하며 관례상 local: 네임스페이스에 둡니다.
(: Built-in functions :)
concat('a', 'b', 'c')
string-join(//title, ', ')
count(//book)
distinct-values(//book/@category)
avg(//book/price)
max(//book/price)
(: User-defined function :)
declare function local:discount($price as xs:decimal)
as xs:decimal {
$price * 0.9
};
local:discount(29.99)XML 구성
XQuery는 직접 생성자(내장 표현식용 { }가 있는 리터럴 태그)나 계산 생성자(element name { ... })로 XML을 만듭니다. 중괄호는 감싼 표현식을 평가하고 속성은 값을 인라인으로 포함할 수 있습니다.
(: Direct element construction :)
<result>
<count>{ count(//book) }</count>
<books>
{ for $b in //book return <book title="{ $b/title/text() }"/> }
</books>
</result>
(: Computed constructors :)
element result {
attribute total { count(//book) },
for $b in //book
return element book { $b/title/text() }
}
(: Enclosed expressions use { } to embed values -->DOM 파싱
XML 로드(JavaScript)
DOMParser는 브라우저에서 XML 문자열을 DOM 트리로 바꿉니다. 파싱 오류는 예외가 아니라 <parsererror> 요소로 나타납니다. Node.js에는 내장 XML DOM이 없으므로 xmldom, @xmldom/xmldom, 스트리밍 파서를 사용하세요.
// Browser: parse an XML string
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "application/xml");
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
console.error("Parse error:", errorNode.textContent);
}
const books = doc.getElementsByTagName("book");
for (const book of books) {
console.log(book.getAttribute("id"));
}
// Node.js: use xmldom or fast-xml-parser insteadDOM 순회
DOM API는 순회용으로 documentElement, children, childNodes, nextSibling을 노출합니다. nodeType 1은 요소, 3은 텍스트, 8은 주석입니다. document.evaluate는 브라우저에서 XPath를 실행합니다(Node에는 xpath 라이브러리 필요).
// JavaScript DOM API (also works for XML documents)
const root = doc.documentElement; // <bookstore>
const firstBook = root.children[0]; // first <book>
const titles = doc.getElementsByTagName("title");
// walk children
let node = root.firstChild;
while (node) {
if (node.nodeType === 1) { // Element node
console.log(node.tagName);
}
node = node.nextSibling;
}
// XPath against the DOM
const it = doc.evaluate("//book[@id='b1']", doc, null,
XPathResult.ANY_TYPE, null);
const found = it.iterateNext();DOM 수정
createElement/setAttribute/appendChild로 노드를 만들고 붙이며 textContent는 텍스트를 설정합니다. XMLSerializer는 DOM을 다시 문자열로 바꿉니다. DOM은 라이브라 변경이 모든 참조에 즉시 반영됩니다.
const book = doc.createElement("book");
book.setAttribute("id", "b3");
const title = doc.createElement("title");
title.textContent = "New Book";
book.appendChild(title);
root.appendChild(book); // add to tree
// change an existing element
const price = doc.querySelector("book:nth-child(2) price");
price.textContent = "19.99";
price.setAttribute("currency", "EUR");
// serialize back to a string
const xml = new XMLSerializer().serializeToString(doc);요소 생성
minidom으로 문서를 처음부터 만들 수 있습니다. 루트에는 createDocument, 내용에는 createElement/setAttribute/createTextNode, 연결에는 appendChild를 사용합니다. toprettyxml은 들여쓰기와 함께 직렬화합니다. minidom은 단순하지만 큰 트리에는 느립니다.
// Python: xml.dom.minidom
from xml.dom import minidom
impl = minidom.getDOMImplementation()
doc = impl.createDocument(None, "root", None)
root = doc.documentElement
item = doc.createElement("item")
item.setAttribute("id", "1")
item.appendChild(doc.createTextNode("Hello"))
root.appendChild(item)
print(doc.toprettyxml(encoding="UTF-8").decode())Java DOM 파싱
Java의 JAXP DOM은 DocumentBuilder로 전체 문서를 메모리에 로드합니다. setNamespaceAware(true)는 네임스페이스 접두사를 유지합니다. DOM은 임의 접근에 편리하지만 큰 파일에는 메모리가 많이 들므로 그럴 때는 StAX/SAX를 선호하세요.
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(true);
Document doc = f.newDocumentBuilder().parse(new File("data.xml"));
Element root = doc.getDocumentElement();
NodeList books = root.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element b = (Element) books.item(i);
String id = b.getAttribute("id");
String title = b.getElementsByTagName("title")
.item(0).getTextContent();
System.out.println(id + ": " + title);
}lxml(Python)
lxml은 libxml2의 빠르고 기능이 풍부한 Python 바인딩입니다. 완전한 XPath, XSLT, 검증(DTD/XSD/RelaxNG), 증분 파싱을 지원합니다. ElementPath(find/findall)는 XPath의 부분 집합이며 완전한 XPath에는 xpath()를 사용하세요.
from lxml import etree
# parse and validate against a schema
tree = etree.parse("data.xml")
root = tree.getroot()
# XPath with namespaces
ns = {"bk": "https://example.com/books"}
for book in root.xpath("//bk:book", namespaces=ns):
print(book.get("id"), book.find("bk:title", namespaces=ns).text)
# build an element tree
root = etree.Element("root")
child = etree.SubElement(root, "item", id="1")
child.text = "Hello"
print(etree.tostring(root, pretty_print=True, encoding="unicode"))SAX 파싱
SAX 핸들러(Python)
SAX는 이벤트 기반 스트리밍입니다. 파서가 읽으면서 startElement, characters, endElement를 호출하고 전체 트리를 만들지 않습니다. 큰 파일에 메모리 효율적입니다. 상태(예: 현재 요소)를 직접 추적해야 합니다.
import xml.sax
class BookHandler(xml.sax.ContentHandler):
def startElement(self, name, attrs):
if name == "book":
print("Book id:", attrs.getValue("id"))
self.current = name
def characters(self, content):
if self.current == "title":
print("Title:", content.strip())
def endElement(self, name):
self.current = None
xml.sax.parse("books.xml", BookHandler())SAX 이벤트 메서드
ContentHandler 콜백은 문서와 요소 경계를 표시합니다. characters()는 하나의 텍스트 노드를 여러 호출로 나눌 수 있으므로 버퍼에 누적하세요. startPrefixMapping/endPrefixMapping은 네임스페이스 선언을 보고합니다.
class Handler(xml.sax.ContentHandler):
def startDocument(self):
print("parsing started")
def endDocument(self):
print("parsing done")
def startElement(self, name, attrs):
# attrs: get via attrs.getValue('id') or attrs['id']
pass
def endElement(self, name):
pass
def characters(self, text):
# may be called multiple times for one text node
pass
def startPrefixMapping(self, prefix, uri):
print("namespace:", prefix, uri)startElement / endElement
요소 경로(스택)를 추적하는 것이 스트리밍 중 위치를 아는 표준 방법입니다. characters() 출력을 버퍼에 모아 endElement에서 flush하세요. characters는 텍스트 노드당 여러 번 발생할 수 있습니다.
class Handler(xml.sax.ContentHandler):
def __init__(self):
self.path = []
self.text = []
def startElement(self, name, attrs):
self.path.append(name)
self.text = []
if "id" in attrs:
print("/".join(self.path), "id =", attrs["id"])
def endElement(self, name):
if self.path[-1] == "title":
print("title:", "".join(self.text).strip())
self.path.pop()
def characters(self, content):
self.text.append(content)Java SAX 파서
Java SAX는 DefaultHandler를 확장합니다. startElement는 네임스페이스 URI, 로컬 이름, 정규화 이름, Attributes 객체를 받습니다. characters(ch, start, len)는 문자 슬라이스를 주므로 텍스트 노드가 여러 호출에 걸칠 수 있어 버퍼링하세요.
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import javax.xml.parsers.*;
class BookHandler extends DefaultHandler {
private StringBuilder buf = new StringBuilder();
public void startElement(String uri, String local,
String qName, Attributes attrs) {
buf.setLength(0);
if ("book".equals(qName))
System.out.println("id=" + attrs.getValue("id"));
}
public void characters(char[] ch, int start, int len) {
buf.append(ch, start, len);
}
public void endElement(String uri, String local, String qName) {
if ("title".equals(qName))
System.out.println("title=" + buf);
}
}
// SAXParserFactory.newInstance().newSAXParser().parse(file, new BookHandler());SAX vs DOM
SAX는 일정한 메모리로 이벤트를 스트리밍해 큰 파일과 단일 패스 추출에 이상적입니다. DOM은 전체 트리를 로드해 XPath와 임의 변경을 가능하게 하지만 파일 크기에 비례하는 메모리를 씁니다. 접근 패턴과 파일 크기로 선택하세요.
<!-- SAX: event-driven, streaming, low memory
DOM: full tree in memory, random access
SAX is best for:
- large files that won't fit in memory
- read-only filtering / extraction
- simple state machines over the document
DOM is best for:
- random access to many parts of the tree
- repeated queries / XPath
- editing and re-serializing -->
<!-- Memory: SAX ~ O(1); DOM ~ O(file size) -->
<!-- Speed: SAX often faster for one-pass scans -->오류 처리(SAX)
ErrorHandler는 경고, 복구 가능한 오류, 치명적 오류를 받습니다. 기본적으로 치명적 오류는 예외를 발생시키고 파싱을 중단합니다. error()를 구현하면 전체 파싱을 중단하지 않고 치명적이지 않은 검증 문제를 로깅할 수 있습니다.
import xml.sax
class Handler(xml.sax.ContentHandler):
pass
# ErrorHandler: warning, error, fatalError
class ErrHandler(xml.sax.ErrorHandler):
def error(self, exception):
print("ERROR:", exception)
def fatalError(self, exception):
print("FATAL:", exception)
raise exception
def warning(self, exception):
print("WARN:", exception)
parser = xml.sax.make_parser()
parser.setContentHandler(Handler())
parser.setErrorHandler(ErrHandler())
parser.parse("data.xml")StAX(풀 파싱)
StAX 커서 API
StAX는 풀 파서입니다. 코드가 next()로 다음 이벤트를 당기므로 루프를 제어합니다. 커서 API(XMLStreamReader)는 이벤 트를 하나씩 이동합니다. DOM보다 빠르고 메모리가 적으며 SAX의 푸시 모델보다 유연합니다.
import javax.xml.stream.*;
import java.io.*;
XMLInputFactory factory = XMLInputFactory.newInstance();
// defend against XXE
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader r = factory.createXMLStreamReader(new FileInputStream("data.xml"));
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
System.out.println("start: " + r.getLocalName());
} else if (event == XMLStreamConstants.END_ELEMENT) {
System.out.println("end: " + r.getLocalName());
}
}
r.close();XMLStreamReader 이벤트
이벤트 타입에는 START_ELEMENT, END_ELEMENT, CHARACTERS, COMMENT, PROCESSING_INSTRUCTION, START/END_DOCUMENT가 있습니다. getText()는 현재 텍스트를 반환하고 isWhiteSpace()는 들여쓰기를 필터링합니다. next() 호출마다 커서가 한 이벤트 전진합니다.
XMLStreamReader r = factory.createXMLStreamReader(in);
while (r.hasNext()) {
switch (r.next()) {
case XMLStreamConstants.START_ELEMENT:
// r.getLocalName(), r.getAttributeValue(i), r.getNamespaceURI()
break;
case XMLStreamConstants.END_ELEMENT:
break;
case XMLStreamConstants.CHARACTERS:
if (!r.isWhiteSpace()) {
String text = r.getText();
}
break;
case XMLStreamConstants.START_DOCUMENT:
break;
case XMLStreamConstants.END_DOCUMENT:
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
break;
}
}요소와 속성 읽기
getAttributeValue(namespaceURI, localName)는 이름으로 속성을 읽습니다(네임스페이스 없으면 null 전달). getElementText()는 텍스트 전용 요소의 텍스트를 읽고 END_ELEMENT를 지나 전진하는 편의 메서드로, 직접 문자를 버퍼링하는 것보다 깔끔합니다.
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT
&& "book".equals(r.getLocalName())) {
String id = r.getAttributeValue(null, "id");
String category = r.getAttributeValue(null, "category");
System.out.println("Book " + id + " (" + category + ")");
}
if (event == XMLStreamConstants.START_ELEMENT
&& "title".equals(r.getLocalName())) {
String title = r.getElementText(); // consumes until END_ELEMENT
System.out.println("Title: " + title);
}
}StAX 라이터
XMLStreamWriter는 XML을 순차적으로 만듭니다. writeStartDocument, writeStartElement/writeEndElement, writeAttribute, writeCharacters, writeNamespace는 균형이 맞아야 합니다. 출력이 완전하도록 마지막에 flush/close하세요.
XMLOutputFactory out = XMLOutputFactory.newInstance();
XMLStreamWriter w = out.createXMLStreamWriter(System.out, "UTF-8");
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("books");
w.writeNamespace("bk", "https://example.com/books");
w.writeStartElement("bk", "book", "https://example.com/books");
w.writeAttribute("id", "b1");
w.writeStartElement("bk", "title", "https://example.com/books");
w.writeCharacters("XML Guide");
w.writeEndElement(); // title
w.writeEndElement(); // book
w.writeEndElement(); // books
w.writeEndDocument();
w.close();StAX vs SAX
SAX는 이벤트를 핸들러로 푸시하고 StAX는 필요할 때 이벤트를 당기게 합니다. StAX의 풀 모델은 하위 트리 건너뛰기와 상태 관리가 쉽고 라이터 API도 추가합니다. 둘 다 전체 DOM 트리를 만들지 않아 큰 문서에 적합합니다.
<!-- StAX: PULL model (client calls next())
SAX: PUSH model (parser calls your handlers)
StAX advantages:
- client controls parsing (easy to skip sections)
- simpler state management for many tasks
- supports both reading and writing
- can pause/resume naturally
SAX advantages:
- slightly lower overhead in pure streaming
- mature, widely available
- filters/chains via XMLFilter
Both are streaming and memory-efficient. -->이벤트 리더(반복자 API)
반복자 API(XMLEventReader)는 엿보고 소비할 수 있는 XMLEvent 객체를 반환합니다. 커서 API보다 객체 지향적이고 필터링이나 분할이 쉽지만 이벤트 객체 할당 때문에 약간 무겁습니다.
import javax.xml.stream.*;
import javax.xml.stream.events.*;
XMLEventReader reader = XMLInputFactory.newInstance()
.createXMLEventReader(in);
while (reader.hasNext()) {
XMLEvent e = reader.peek(); // look without consuming
if (e.isStartElement()) {
StartElement se = e.asStartElement();
System.out.println(se.getName());
}
XMLEvent consumed = reader.nextEvent(); // consume it
if (consumed.isEndElement()) {
System.out.println("closed");
}
}
reader.close();XML과 JSON 변환
XML to JSON(JavaScript)
fast-xml-parser는 Node.js에서 XML을 JSON으로 변환합니다. 속성에는 접두사(기본 @_)가 붙고 반복 요소는 배열이 됩니다. 순수 JavaScript라 빠르며 배열, 숫자, 불리언 처리를 제어하는 옵 션이 있습니다.
// Node.js with fast-xml-parser
const { XMLParser } = require("fast-xml-parser");
const xml = "<book id='b1'><title>XML</title><price>29.99</price></book>";
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
});
const json = parser.parse(xml);
console.log(json.book["@_id"]); // b1
console.log(json.book.title); // XML
console.log(json.book.price); // 29.99JSON to XML(JavaScript)
XMLBuilder는 변환을 역으로 합니다. @_ 접두사는 속성을 표시하고 중첩 객체는 자식 요소가 됩니다. 배열은 반복 요소를 만듭니다. XML의 단일 루트 규칙 때문에 최상위 JSON 객체는 하나의 루트 요소로 매핑되어야 합니다.
const { XMLBuilder } = require("fast-xml-parser");
const json = {
book: {
"@_id": "b1",
title: "XML Guide",
price: 29.99,
},
};
const builder = new XMLBuilder({
format: true,
attributeNamePrefix: "@_",
ignoreAttributes: false,
});
const xml = builder.build(json);
console.log(xml);
// <book id="b1">
// <title>XML Guide</title>
// <price>29.99</price>
// </book>Python xmltodict
xmltodict는 XML을 dict/list 구조처럼 다룹니다. 속성은 '@name', 텍스트는 '#text'를 씁니다. parse()는 XML을 읽고 unparse()는 씁니다. 빠른 왕복에 좋지만 복잡한 스키마에서는 순서와 일부 경계 사례를 잃습니다.
import xmltodict, json
xml = """<book id="b1"><title>XML</title><price>29.99</price></book>"""
# XML -> dict
data = xmltodict.parse(xml)
print(data["book"]["@id"]) # b1
print(data["book"]["title"]) # XML
# dict -> JSON
print(json.dumps(data, indent=2))
# dict -> XML
xml_out = xmltodict.unparse({"book": {"@id": "b2", "title": "New"}})
print(xml_out)속성과 텍스트 처리
XML을 JSON으로 변환하면 속성(@_ 접두사), 텍스트(#text), 혼합 콘텐츠에 대한 결정이 필요합니다. 텍스트와 자식 요소가 섞인 혼합 콘텐츠는 JSON에 깔끔하게 매핑되지 않고 종종 충실도를 잃습니다. 관례를 정하고 일관되게 유지하세요.
<!-- XML with mixed attributes and text -->
<product sku="A1" stock="5">Widget<note>sale</note></product>
// fast-xml-parser output:
// {
// product: {
// "@_sku": "A1",
// "@_stock": "5",
// "#text": "Widget",
// note: "sale"
// }
// }
// Round-trip carefully: mixed content (text + elements)
// is hard to represent losslessly in JSON -->변환 과제
흔한 변환 함정: 단일 vs 다중 자식(배열 vs 문자열), 요소 순서, 네임스페이스 접두사(별칭), 단일 루트 제약, 원시 타입(XML에는 네이티브 숫자나 불리언이 없음). 관례를 문서화하세요.
<!-- 1. Repeated elements -> array -->
<list><item>a</item><item>b</item></list>
// { list: { item: ["a", "b"] } } (or single string if only one)
<!-- 2. Order is significant in XML but not in JSON objects -->
<a><x/><y/></a> vs <a><y/><x/></a> // may differ
<!-- 3. Namespaces -->
<ns:elem xmlns:ns="http://x"/> // prefixes are aliases
<!-- 4. Single root: JSON top-level must be one object -->
<!-- 5. Numbers/booleans: XML is all text; typing is heuristic -->왕복 예제
왕복(XML -> JSON -> XML)은 잘 구조화된 데이터에는 동작하지만 주석, 처리 명령, CDATA 경계, 정확한 공백을 잃을 수 있습니다. 무손실 편집에는 JSON 변환 대신 DOM/트리 API를 사용하세요.
// Parse, modify, and re-serialize with fast-xml-parser
const { XMLParser, XMLBuilder } = require("fast-xml-parser");
const opts = { ignoreAttributes: false, attributeNamePrefix: "@_" };
const parser = new XMLParser(opts);
const builder = new XMLBuilder({ ...opts, format: true });
const obj = parser.parse(xmlString);
// mutate
obj.book.price = 19.99;
obj.book["@_onSale"] = "true";
const newXml = builder.build(obj);
console.log(newXml);RSS와 Atom 피드
RSS 2.0 구조
RSS 2.0은 하나의 <channel>을 가진 <rss> 루트가 있습니다. 필수 채널 필드: title, link, description. 각 <item>에는 title, link, description, guid, pubDate가 있습니다. 날짜는 RFC 822를 따릅니다(예: 'Wed, 02 Oct 2024 13:00:00 GMT').
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>My Blog</title>
<link>https://example.com</link>
<description>Recent posts</description>
<language>en-us</language>
<pubDate>Wed, 02 Oct 2024 13:00:00 GMT</pubDate>
<item>
<title>First Post</title>
<link>https://example.com/1</link>
<description>A short summary</description>
<pubDate>Wed, 02 Oct 2024 12:00:00 GMT</pubDate>
<guid>https://example.com/1</guid>
</item>
</channel>
</rss>RSS 채널과 항목
채널 수준 필드는 피드를 설명합니다(title, link, description, language, ttl, image). 항목 필드는 각 항목을 설명하고 enclosure는 URL, 바이트 길이, MIME 타입과 함께 팟캐스트/미디어를 지원합니다. category는 domain 속성을 가질 수 있습니다.
<channel>
<title>Site Title</title>
<link>https://example.com</link>
<description>What the feed is about</description>
<category>Technology</category>
<ttl>60</ttl> <!-- cache minutes -->
<image>
<url>https://example.com/logo.png</url>
<title>Site Title</title>
<link>https://example.com</link>
</image>
<item>
<title>Post Title</title>
<link>https://example.com/post</link>
<description>Summary text</description>
<author>[email protected]</author>
<category domain="https://example.com/tags">xml</category>
<enclosure url="https://example.com/p.mp3" length="12345"
type="audio/mpeg"/>
</item>
</channel>Atom 피드
Atom(RFC 4287)은 Atom 네임스페이스의 <feed> 루트를 씁니다. 필수: id, title, updated. 항목에는 id, title, updated가 필요합니다. id는 전역 고유(URN 또는 tag: URI)여야 합니다. 날짜는 시간대가 있는 RFC 3339(ISO 8601)를 씁니다.
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="https://example.com/feed.atom" rel="self"/>
<link href="https://example.com"/>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<updated>2024-10-02T13:00:00Z</updated>
<author><name>Jane Doe</name></author>
<entry>
<title>Atom Entry</title>
<id>tag:example.com,2024:/post/1</id>
<updated>2024-10-02T12:00:00Z</updated>
<summary>A short summary</summary>
<content type="html"><p>Full post body</p></content>
</entry>
</feed>Atom 항목 세부
Atom 항목은 type 속성으로 text, html, xhtml의 풍부한 콘텐츠를 지원합니다. link는 rel 속성(alternate, self, enclosure, related)을 씁니다. category에는 term/scheme/label이 있습니다. published는 원래 날짜, updated는 마지막 변경입니다.
<entry>
<title type="text">Post Title</title>
<id>tag:example.com,2024:/posts/42</id>
<updated>2024-10-02T12:00:00Z</updated>
<published>2024-10-01T09:00:00Z</published>
<author>
<name>Jane Doe</name>
<email>[email protected]</email>
<uri>https://example.com/jane</uri>
</author>
<link href="https://example.com/posts/42" rel="alternate"/>
<category term="xml" scheme="https://example.com/tags" label="XML"/>
<summary type="text">A teaser.</summary>
<content type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml"><p>Body</p></div>
</content>
</entry>흔한 피드 네임스페이스
RSS는 모듈로 확장되는 경우가 많습니다: Dublin Core(dc:creator, dc:date), content(전체 HTML용 content:encoded), Media RSS(media:content), 리더가 피드 URL을 찾게 돕는 atom:link rel='self'. 네임스페이스로 피드가 어휘를 섞을 수 있습니다.
<?xml version="1.0"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Feed</title>
<link>https://example.com</link>
<description>desc</description>
<atom:link href="https://example.com/feed.xml" rel="self"
type="application/rss+xml"/>
<item>
<title>Post</title>
<dc:creator>Jane Doe</dc:creator>
<content:encoded><![CDATA[<p>HTML body</p>]]></content:encoded>
<media:content url="https://example.com/img.png" medium="image"/>
</item>
</channel>
</rss>피드 검증
W3C Feed Validator로 RSS/Atom을 검사하세요. 흔한 오류: 필수 필드 누락, 잘못된 날짜 형식, 고유하지 않은 id, 잘못된 XML(이스케이프 안 된 &), self 링크 누락. 유효한 피드는 애그리게이터가 안정적으로 파싱하게 합니다.
<!-- RSS: dates must be RFC 822, e.g. -->
<pubDate>Wed, 02 Oct 2024 13:00:00 GMT</pubDate>
<!-- Atom: dates must be RFC 3339, e.g. -->
<updated>2024-10-02T13:00:00Z</updated>
<!-- Validate online with https://validator.w3.org/feed/ -->
<!-- Required RSS channel fields: title, link, description -->
<!-- Required Atom feed fields: id, title, updated -->
<!-- GUIDs/IDs should be unique and permanent -->SVG와 XML
SVG 문서 구조
SVG는 벡터 그래픽을 위한 XML 어휘입니다. 루트 <svg>는 SVG 네임스페이스와 좌표계용 viewBox를 선언합니다. 모든 그래픽 요소(rect, circle, text)는 표현 속성을 가진 XML 요소입니다.
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200" height="200" viewBox="0 0 200 200">
<rect x="10" y="10" width="180" height="180"
fill="#005FAD" stroke="black" stroke-width="2"/>
<circle cx="100" cy="100" r="40" fill="white"/>
<text x="100" y="105" text-anchor="middle">SVG</text>
</svg>
<!-- SVG is an XML application; it must be well-formed -->SVG 네임스페이스와 가져오기
SVG 요소는 http://www.w3.org/2000/svg 네임스페이스에 있습니다. SVG 1.1에서는 href 참조에 xlink를 쓰고 SVG 2는 일반 href를 선호합니다. defs는 url(#id)로 참조하는 재사용 그라디언트, 패턴, 심볼을 담습니다.
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1">
<defs>
<linearGradient id="g1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
</defs>
<rect width="100" height="100" fill="url(#g1)"/>
</svg>SVG 도형
SVG 도형 요소: rect(둥근 모서리용 rx/ry), circle, ellipse, line, polyline(열림), polygon(닫힘). 좌표는 viewBox가 정의한 사용자 단위입니다. stroke와 fill이 흔한 표현 속성입니다.
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
<rect x="10" y="10" width="80" height="50" rx="10" fill="teal"/>
<circle cx="150" cy="60" r="40" fill="orange"/>
<ellipse cx="220" cy="60" rx="50" ry="20" fill="purple"/>
<line x1="10" y1="120" x2="290" y2="120" stroke="black"/>
<polyline points="10,180 50,140 90,180 130,140" fill="none" stroke="red"/>
<polygon points="200,180 250,140 280,200" fill="green"/>
</svg>SVG 텍스트와 패스
SVG 텍스트는 font-family, font-size, font-weight, font-style을 씁니다. tspan은 텍스트 요소 안에서 스타일을 섞게 합니다. path 요소의 'd' 속성은 M(이동), L(선), C(3차 베지어), Q(2차), A(호), Z(경로 닫기) 명령을 씁니다.
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="150">
<text x="10" y="40" font-family="Arial" font-size="24"
font-weight="bold" fill="navy">Hello SVG</text>
<text x="10" y="80">
<tspan font-size="16">Normal</tspan>
<tspan font-size="16" font-style="italic"> italic</tspan>
</text>
<path d="M10 100 L 100 100 L 55 140 Z"
fill="none" stroke="black" stroke-width="2"/>
</svg>
<!-- Path commands: M=move, L=line, H/V, C=cubic, Q=quad, A=arc, Z=close -->SVG 그룹화와 재사용
<g> 요소는 공유 스타일과 변환을 위해 도형을 묶습니다. <use>는 id로 요소를 참조하고(SVG 2는 href='#id', 1.1은 xlink:href) 새 위치에 복제합니다. <symbol>은 <use>로만 렌더링되는 재사용 그래픽을 정의합니다.
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<g id="node" stroke="black" fill="lightblue">
<circle cx="50" cy="50" r="20"/>
<circle cx="100" cy="50" r="20"/>
</g>
<use href="#node" x="0" y="100"/>
<use href="#node" x="0" y="150" opacity="0.5"/>
<symbol id="star" viewBox="0 0 24 24">
<polygon points="12,2 15,9 22,9 17,14 19,21 12,17 5,21 7,14 2,9 9,9"/>
</symbol>
<use href="#star" width="24" height="24"/>
</svg>SVG 검증
SVG 문서는 W3C DTD나 XSD로 검증할 수 있습니다. 흔한 문제: SVG 네임스페이스 누락, 선언되지 않은 접두사, 잘못된 네임스페이스의 속성, 잘못된 패스 데이터. xmllint가 표준 명령줄 검증기입니다.
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect width="100" height="100"/>
</svg>
<!-- Validate with xmllint: -->
<!-- xmllint --noout --valid file.svg (DTD) -->
<!-- xmllint --noout --schema svg11.xsd file.svg (XSD) -->
<!-- Common errors: wrong namespace, undeclared prefixes,
text outside a text element, invalid path data -->SOAP과 WSDL
SOAP 엔벨로프
SOAP 메시지는 SOAP 네임스페이스의 <Envelope> 루트를 가진 XML 문서입니다. 선택적 <Header>는 메타데이터(인증, 라우팅)를, 필수 <Body>는 실제 메시지 페이로드를 담습니다. SOAP 1.1과 1.2는 다른 네임스페이스를 씁니다.
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<auth xmlns="https://example.com/auth">
<token>abc123</token>
</auth>
</soap:Header>
<soap:Body>
<m:GetPrice xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
<!-- Envelope is the root; Header is optional, Body is required -->SOAP 헤더
헤더는 인증, 주소 지정(WS-Addressing), 트랜잭션 같은 대역 외 정보를 담습니다. soap:mustUnderstand='1'은 수신자가 이 헤더를 반드시 처리하거나 SOAP fault를 반환해야 함을 알려 계약 준수를 강제합니다.
<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<wsa:Action xmlns:wsa="http://www.w3.org/2005/08/addressing">
http://example.com/GetPrice
</wsa:Action>
<wsa:MessageID>urn:uuid:1234</wsa:MessageID>
<auth xmlns="https://example.com/auth"
soap:mustUnderstand="1">
<token>secret</token>
</auth>
</soap:Header>
<!-- mustUnderstand="1" forces the receiver to process the header -->SOAP Body와 Fault
Body는 요청이나 응답 페이로드를 담습니다. 오류 시 Body에는 faultcode(Client/Server), 사람이 읽을 수 있는 faultstring, 선택적 detail이 있는 <Fault>가 들어갑니다. SOAP 1.2는 이 요소 이름을 바꾸고 Code/Reason 구조를 추가합니다.
<!-- Request body -->
<soap:Body>
<m:GetPrice xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
<!-- Fault (error response) -->
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Unknown item: Apples</faultstring>
<detail>
<m:Error xmlns:m="https://example.com/pricing">
<code>404</code>
</m:Error>
</detail>
</soap:Fault>
</soap:Body>WSDL 구조
WSDL은 웹 서비스를 설명합니다: <types>(XSD 스키마), <message>(입출력 페이로드), <portType>(인터페이스, 연산과 메시지), <binding>(프로토콜/인코딩), <service>(엔드포인트 URL). WSDL 2.0은 이를 인터페이스와 바인딩으로 단순화합니다.
<?xml version="1.0"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/pricing">
<types>
<xs:schema targetNamespace="https://example.com/pricing">
<xs:element name="GetPriceRequest" type="xs:string"/>
<xs:element name="GetPriceResponse" type="xs:decimal"/>
</xs:schema>
</types>
<message name="GetPriceInput">
<part name="item" element="tns:GetPriceRequest"/>
</message>
<portType name="PricingPort">
<operation name="GetPrice">
<input message="tns:GetPriceInput"/>
<output message="tns:GetPriceOutput"/>
</operation>
</portType>
</definitions>WSDL 바인딩과 서비스
바인딩은 portType을 구체 프로토콜(HTTP 위 SOAP)과 스타일(document/literal이 현대 기본)에 매핑합니다. service 요소는 엔드포인트(soap:address)를 나열합니다. document/literal은 페이로드를 스키마 정의 요소로 감쌉니다.
<binding name="PricingSOAP" type="tns:PricingPort">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetPrice">
<soap:operation soapAction="http://example.com/GetPrice"/>
<input><soap:body use="literal"/></input>
<output><soap:body use="literal"/></output>
</operation>
</binding>
<service name="PricingService">
<port name="PricingPort" binding="tns:PricingSOAP">
<soap:address location="https://example.com/pricing"/>
</port>
</service>
<!-- style: rpc or document; use: encoded or literal -->SOAP vs REST
SOAP은 엄격한 XML 엔벨로프, WSDL 계약, WS-* 표준(보안, 트랜잭션)을 갖춘 프로토콜로 신뢰성과 공식 계약이 필요한 엔터프라이즈 통합에 적합합니다. REST는 보통 JSON을 쓰는 가벼운 HTTP 기반 스타일로 공개 API를 지배합니다.
<!-- SOAP: protocol with envelope, strict contract (WSDL),
built-in error model (Fault), WS-* extensions.
Heavier, XML-only, common in enterprise/B2B. -->
<!-- REST: architectural style using HTTP verbs (GET/POST/...),
flexible payloads (often JSON), no built-in contract.
Lighter, browser-friendly, dominant on the web. -->
<!-- When to use SOAP:
- you need strict contracts and tooling
- transactional reliability (WS-ReliableMessaging)
- standardized security (WS-Security)
- existing SOAP-based infrastructure -->
<!-- When to use REST:
- public APIs, mobile/web clients
- JSON payloads, HTTP caching
- simpler, faster iteration -->XML 디지털 서명
서명 구조
XML 서명의 루트 <Signature>에는 <SignedInfo>(무엇을 어떻게 서명하는지), <SignatureValue>(정규화된 SignedInfo에 대한 암호 서명), 선택적 <KeyInfo>, 참조 데이터를 담는 <Object>가 있습니다.
<?xml version="1.0"?>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="..."/>
<SignatureMethod Algorithm="..."/>
<Reference URI="#data">
<DigestMethod Algorithm="..."/>
<DigestValue>...</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>...</SignatureValue>
<KeyInfo>...</KeyInfo>
<Object Id="data">signed content</Object>
</Signature>
<!-- A signature = SignedInfo + SignatureValue + optional KeyInfo -->SignedInfo
SignedInfo는 정규화(XML 재직렬화에도 바이트 동일 서명이 유지되도록), 서명 알고리즘, 하나 이상의 Reference를 지정합니다. 각 Reference는 URI로 데이터를 가리키고 Transforms를 나열하며 그 데이터의 DigestValue를 제공합니다.
<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<CanonicalizationMethod
Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod
Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="...enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>base64digest==</DigestValue>
</Reference>
</SignedInfo>Reference와 Transforms
각 Reference는 서명할 대상(URI)을 식별하고 Transforms(정규화, XPath 필터링, enveloped-signature 제거)를 적용한 뒤 DigestMethod로 해시합니다. enveloped-signature 변환은 Signature 요소 자체를 자신의 해시에서 제외합니다.
<Reference URI="#order">
<Transforms>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<XPath xmlns="...">not(ancestor-or-self::ds:Signature)</XPath>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>abc123base64==</DigestValue>
</Reference>
<!-- Reference types:
- same-document (URI="#id")
- external (URI="https://...")
- detached (URI pointing elsewhere) -->SignatureValue와 KeyInfo
SignatureValue는 정규화된 SignedInfo를 서명자의 개인 키로 서명한 base64 결과입니다. KeyInfo는 선택이며 검증 키(X.509 인증서, RSA 공개 키, 키 이름, 검색 URL)를 찾는 힌트일 뿐이므로 대역 외에서 검증해야 합니다.
<SignatureValue>base64encodedSignature==</SignatureValue>
<KeyInfo>
<X509Data>
<X509SubjectName>CN=Example,O=Example Inc</X509SubjectName>
<X509Certificate>MIID...base64...==</X509Certificate>
</X509Data>
</KeyInfo>
<!-- Other KeyInfo options: -->
<!-- <KeyName>key-id</KeyName> -->
<!-- <KeyValue><RSAKeyValue>...</RSAKeyValue></KeyValue> -->
<!-- <RetrievalMethod URI="..."/> -->
<!-- KeyInfo is optional and unverified by itself -->정규화
정규화는 XML 노드 집합을 안정적인 바이트로 변환해 속성 순서나 CDATA 같은 무관한 차이에도 서명을 재현 가능하게 합니다. 배타적 c14n(xml-exc-c14n)은 네임스페이스를 서명된 하위 트리로 범위를 한정하므로 서명에 선호됩니다.
<!-- Two documents that are logically identical may differ in bytes:
- attribute order
- namespace declarations
- CDATA vs escaping
- whitespace outside elements
Canonical XML (c14n) produces a canonical byte form. -->
<CanonicalizationMethod
Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<!-- Exclusive c14n (recommended for signatures): -->
<CanonicalizationMethod
Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<!-- Exclusive form avoids leaking inherited namespace declarations
into the signed digest, preventing wrapping attacks. -->엔벨로프 서명
엔벨로프 서명은 서명하는 문서 안에 포함됩니다(XML에서 가장 흔함). enveloped-signature 변환이 해시 전에 <Signature> 요소를 제거해 서명이 자신의 다이제스트에 포함되지 않게 합니다. 분리형과 포위형 변형도 있습니다.
<?xml version="1.0"?>
<order Id="order">
<item>Widget</item>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="...exc-c14n#"/>
<SignatureMethod Algorithm="...rsa-sha256"/>
<Reference URI="#order">
<Transforms>
<Transform Algorithm="...enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="...sha256"/>
<DigestValue>...</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>...</SignatureValue>
</Signature>
</order>
<!-- The signature lives INSIDE the signed element -->XLink와 XPointer
XLink 단순 링크
XLink 단순 링크는 임의 XML에서 HTML 앵커를 모방합니다. xlink:type='simple'은 기본 단방향 링크를 만들고 xlink:href가 대상입니다. show는 표시(new/replace/embed)를, actuate는 타이밍(onRequest/onLoad)을 제어합니다.
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<web xlink:type="simple"
xlink:href="https://example.com"
xlink:role="https://example.com/roles/home"
xlink:title="Example Site"
xlink:show="new"
xlink:actuate="onRequest">
Visit Example
</web>
</root>
<!-- A simple link is a one-way hyperlink, similar to HTML <a> -->XLink 확장 링크
확장 링크는 아크를 통해 여러 리소스(로케이터)를 연결합니다. 각 로케이터에는 레이블이 있고 아크는 레이블 간 이동(from/to)을 정의합니다. 외부 링크는 별도 문서에 있을 수 있어 제3자 리소스 간 다방향 연결을 가능하게 합니다.
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<link xlink:type="extended" xlink:role="https://example.com/mapping">
<loc xlink:type="locator" xlink:label="src"
xlink:href="https://a.example/doc1" xlink:title="Doc A"/>
<loc xlink:type="locator" xlink:label="dst"
xlink:href="https://b.example/doc2" xlink:title="Doc B"/>
<go xlink:type="arc" xlink:from="src" xlink:to="dst"
xlink:show="new" xlink:actuate="onRequest"/>
</link>
</root>
<!-- Extended links can connect multiple resources and be out-of-line -->XLink 속성
XLink 속성은 타입별로 나뉩니다. href는 로케이터/리소스를 가리키고 label은 아크 참여자 이름을, from/to는 아크를 연결합니다. role/arcrole은 의미 URI(흔히 Dublin Core나 RELAX NG 용어)입니다. show/actuate는 표시와 로딩 동작을 구동합니다.
<!-- xlink:type: simple | extended | locator | arc | resource | title | none -->
<!-- Common attributes by type -->
<el xlink:type="simple" xlink:href="..." xlink:role="..." xlink:title="..."
xlink:show="new|replace|embed|other|none"
xlink:actuate="onRequest|onLoad|other|none"/>
<el xlink:type="locator" xlink:href="..." xlink:label="..." xlink:role="..."/>
<el xlink:type="arc" xlink:from="..." xlink:to="..." xlink:show="..."/>
<el xlink:type="resource" xlink:label="..." xlink:role="..."/>
<!-- xlink:role is a URI identifying the resource's meaning -->
<!-- xlink:arcrole describes the arc (relationship) itself -->XPointer 기초
XPointer는 URI 프래그먼트로 XML 문서 내 위치를 지정합니다. 축약형(#id)은 ID로 선택합니다. 스킴 기반 형식(#xpointer(...))은 XPath를 쓰고 element()는 위치 기반 자식 경로를 씁니다. 프래그먼트는 문서를 가져온 후 해석됩니다.
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- XPointer extends a URI fragment to address XML parts -->
<link xlink:type="simple"
xlink:href="doc.xml#xpointer(//book[@id='b1'])"/>
<link xlink:href="doc.xml#xpointer(/root/section[2]/p[1])"/>
<link xlink:href="doc.xml#b1"/>
</root>
<!-- Fragment forms:
- shorthand: #id
- scheme-based: #xpointer(expr)
- element(): #element(/1/2/3) -->XPointer 프레임워크
XPointer 프레임워크는 여러 스킴을 연결해 앞의 것이 실패하면 다음을 시도합니다. xmlns() 스킴은 뒤따르는 xpointer() 표현식에서 쓸 접두사를 바인딩합니다. element()는 ID와 무관한 견고한 위치 경로를 제공합니다.
<!-- The XPointer Framework defines how fragment schemes compose -->
<ref xlink:href="doc.xml#element(/1/2)"/>
<ref xlink:href="doc.xml#xpointer(//section[@id='s1']/p[2])"/>
<ref xlink:href="doc.xml#xmlns(bk=https://example.com/b)xpointer(//bk:book)"/>
<!-- Multiple schemes can be tried in order: -->
<ref xlink:href="doc.xml#element(/1/2)xpointer(//book[@id='b1'])"/>
<!-- If element() fails, the next scheme is attempted -->
<!-- Common schemes: element(), xpointer(), xmlns(), xpath1() -->element() 스킴
element() 스킴은 1부터 시작하는 자식 위치 시퀀스로 노드를 지정하며 선택적으로 ID가 있는 요소에서 시작합니다. 요소 이름이 아니라 구조에만 의존하므로 스키마 변경에 xpointer()보다 견고합니다.
<!-- element() addresses by child positions from the root -->
<ref xlink:href="doc.xml#element(/1/2/3)"/>
<!-- selects the 1st child of root, its 2nd child, then 3rd child -->
<!-- or relative to an ID -->
<ref xlink:href="doc.xml#element(b1/2)"/>
<!-- the 2nd child of the element with id="b1" -->
<!-- child positions are 1-based and skip text/attribute nodes;
only element children are counted -->명명 규칙
요소 이름
스타일을 선택해 일관되게 적용하세요. XML 어휘(HTML, SVG)에는 소문자-하이픈이 흔합니다. 이름은 모호하지 않을 만큼 설명적이되 간결해야 합니다. 알아보기 어려운 약어와 지나치게 장황한 이름을 피하세요.
<!-- Good: lowercase, hyphen-separated, descriptive -->
<customer-address>
<street>123 Main St</street>
<postal-code>12345</postal-code>
</customer-address>
<!-- Avoid: abbreviations that are unclear -->
<!-- <cust-addr><pc>...</pc></cust-addr> -->
<!-- Avoid: too long -->
<!-- <customerMailingPostalAddressCode> -->
<!-- Be consistent across the whole vocabulary -->속성 이름
속성은 메타데이터(id, type, href, status)에 적합합니다. 요소 명명 스타일과 맞추세요. 불리언은 명시적 값을 가집니다. 속성에 요소 이름을 접두사로 붙이지 마세요(<user>의 user-id는 중복). 고유 식별자에는 'id'를 사용하세요.
<product sku="A1" unit-price="9.99" in-stock="true">
<name>Widget</name>
</product>
<!-- Conventions:
- attributes are metadata: id, type, href, status
- use lowercase-hyphen style to match elements
- boolean attributes still carry a value ("true"/"false")
- avoid repeating the element name: <user user-id="..."/>
prefer <user id="..."/> -->
<!-- IDs: use 'id' or '<element>-id' for clarity -->네임스페이스 URI와 접두사
네임스페이스 URI는 가져올 수 있는 URL이 아니라 식별자이지만 안정적이고 소유되어야 합니다(통제하는 도메인의 HTTPS 사용). 접두사는 로컬 별칭이므로 짧고 관례적으로 유지하세요. 스키마가 호환되지 않게 바뀌면 URI 버전을 올리세요.
<!-- Namespace URIs should be stable, owned, and permanent -->
xmlns:bk = "https://example.com/ns/books/2024"
xmlns:auth= "https://example.com/ns/auth"
<!-- Prefix conventions:
- short and mnemonic: xs, xsi, xsl, svg, html, dc
- lowercase, no punctuation beyond letters
- 'tns' commonly means 'this namespace' in XSD
- avoid 'xml' (reserved) -->
<!-- Version the URI when the vocabulary changes incompatibly:
.../ns/books/2024 vs .../ns/books/2025 -->대소문자 스타일
흔한 XML 케이스 스타일: PascalCase(XSD/WSDL, .NET), camelCase(JSON 유래, Java), 소문자-하이픈(HTML/SVG, REST 친화적), snake_case(드묾). 핵심 규칙은 한 어휘 안에서 일관성이며 스타일을 섞으면 혼란스럽습니다.
<!-- PascalCase (UpperCamelCase): common in XSD/WSDL, .NET -->
<OrderRequest>
<CustomerId>123</CustomerId>
</OrderRequest>
<!-- camelCase: common in JSON-derived XML, Java ecosystems -->
<orderRequest>
<customerId>123</customerId>
</orderRequest>
<!-- lowercase-with-hyphens: HTML5, SVG, REST-friendly -->
<order-request>
<customer-id>123</customer-id>
</order-request>
<!-- snake_case: rare in XML, used in some Python/SQL ecosystems -->
<order_request><customer_id>123</customer_id></order_request>버전 관리
XML 어휘를 명시적으로 버전 관리하세요. 루트의 version 속성이 가장 단순하고 버전이 붙은 네임스페이스 URI가 가장 엄격합니다(호환되지 않는 변경은 새 URI). 마이너(추가) 변경과 메이저(파괴) 변경의 기준을 정하고 문서화하세요.
<!-- Versioning strategies -->
<!-- 1. Attribute on the root -->
<catalog version="2.0">...</catalog>
<!-- 2. Versioned namespace URI -->
<catalog xmlns="https://example.com/ns/catalog/v2">...</catalog>
<!-- 3. Versioned root element name -->
<catalog-v2>...</catalog-v2>
<!-- Backward-compatible changes: add optional elements/attributes
Incompatible changes: bump the version (and/or namespace) -->
<!-- Document the policy: which changes are "minor" vs "major" -->파일과 확장자 관례
도구와 사람이 파일 타입을 식별하도록 인식되는 확장자를 사용하세요. XML 선언의 encoding 속성은 실제 바이트 인코딩과 일치해야 하며 UTF-8이 안전한 기본입니다. UTF-8 XML에는 BOM을 권장하지 않습니다.
<!-- Common file extensions:
.xml generic XML
.xsd XML Schema
.xsl XSLT stylesheet
.xslt XSLT (alternate)
.dtd Document Type Definition
.rss RSS feed
.atom Atom feed
.svg SVG graphic
.wsdl WSDL service description
.xhtml XHTML document
.plist Apple property list -->
<!-- XML files are UTF-8 by default; declare encoding if different:
<?xml version="1.0" encoding="UTF-8"?> -->모범 사례
잘 형성됨이 먼저
어떤 도구가 처리하려면 문서가 먼저 잘 형성되어야 합니다. 파서로 일찍 검증하세요. xmllint --noout file.xml이 첫 오류를 보고합니다. 잘 형성됨은 협상 불가이고 스키마 유효성은 추가적이고 선택적인 계층입니다.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>properly nested & escaped</child>
</root>
<!-- Always ensure well-formedness before worrying about validity:
- exactly one root element
- all tags closed and properly nested
- attributes quoted and unique per element
- & < escaped (and > in some contexts)
- valid encoding declaration -->검증과 스키마
스키마로 검증해 구조 오류를 잡으세요. 타입이 있고 네임스페이스가 있는 어휘에는 XSD가 가장 흔하고 Schematron이 비즈니스 규칙으로 보완합니다. xsi:noNamespaceSchemaLocation은 문서를 XSD에 연결하고 네임스페이스 스키마에는 xsi:schemaLocation을 사용하세요.
<!-- Choose a schema language:
- DTD: simple, built-in, limited types
- XSD: rich types, namespaces, industry standard
- RelaxNG: compact syntax, flexible patterns
- Schematron: rule-based business constraints -->
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="schema.xsd">
<item>valid</item>
</root>
<!-- Validate during development; consider it at runtime for
untrusted input. -->인코딩(UTF-8)
UTF-8은 XML의 기본이자 권장 인코딩으로 엔티티 없이 모든 유니코드를 처리합니다. 항상 인코딩을 선언하고 그 인코딩으로 파일을 저장하세요. BOM을 피하고 특수 문자에는 숫자 문자 참조를 쓸 수도 있습니다.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<msg>Café — résumé — 中文 — emoji 🙂</msg>
</root>
<!-- Always declare UTF-8 and save the file as UTF-8.
Avoid legacy encodings (ISO-8859-1) unless required.
Do not add a UTF-8 BOM (some parsers mishandle it).
For non-UTF-8 encodings, declare them accurately. -->가독성과 들여쓰기
일관된 들여쓰기(보통 2칸)는 XML을 읽기 쉽고 diff를 깔끔하게 만듭니다. 긴 한 줄은 피하세요. 'xmllint --format'이나 XML 포매터가 공백을 정규화할 수 있지만 xml:space='preserve' 영역은 재포맷하면 안 됩니다.
<?xml version="1.0"?>
<catalog>
<book id="b1">
<title>XML Guide</title>
<author>Jane Doe</author>
</book>
<book id="b2">
<title>Advanced XML</title>
<author>John Smith</author>
</book>
</catalog>
<!-- Use 2-space indentation; one element per line for mixed
or deep structures. Tools: xmllint --format, prettier. -->성능
큰 파일에는 메모리를 낮게 유지하도록 DOM보다 스트리밍 파서(SAX/StAX)를 선호하세요. 필요하지 않으면 DTD 로딩과 외부 엔티티를 비활성화하세요. XPath 표현식을 한 번 컴파일해 재사용하세요. 내부 시스템에는 크기와 파싱 시간을 줄이는 압축 바이너리 형식을 고려하세요.
<!-- Parsing large XML efficiently:
- use SAX/StAX (streaming) instead of DOM for big files
- disable DTD/external entities if you don't need them
- validate once, not on every read
- reuse parser instances (factory creation is costly)
- consider binary formats (protobuf, CBOR) for internal traffic -->
<!-- Java StAX with XXE disabled:
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); -->
<!-- For repeated XPath, compile once and reuse the expression -->보안(XXE)
XML 외부 엔티티(XXE) 공격은 DTD 외부 엔티티를 악용해 파일을 읽거나 SSRF를 트리거하거나 서비스 거부(billion laughs/엔티티 확장)를 일으킵니다. 가장 강력한 방어는 사용 사례에 필요하지 않다면 DTD와 외부 엔티티 해석을 완전히 비활성화하는 것입니다.
<?xml version="1.0"?>
<!DOCTYPE root [
<!-- XXE: attacker forces the parser to read a local file -->
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>
<!-- Defenses (do ALL that apply):
1. Disable DTDs entirely if you don't need them.
2. Disable external entity resolution.
3. Disable XInclude.
4. Validate input; limit entity expansion (billion laughs). -->
<!-- Python: defusedxml
Java: XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES = false
PHP: libxml_disable_entity_loader(true) -->관련 XML 스니펫
Copy-paste ready code for common tasks.
Namespaces
Declare and use XML namespaces.
XPath
Path expressions for selecting nodes.
DTD and Schema
Document Type Definition for validation.
DOM and SAX Parsing
Two models for reading XML.
Attributes
Name-value pairs on elements.
CDATA Sections
Escape blocks of literal text.
XSLT
Transform XML into other formats.
Well-Formed XML
Rules every parser enforces.
Was this helpful?