0
# Namespace Support
1
2
Comprehensive XML namespace support including namespace builders, QName factories, and namespace-aware parsing and generation across all processing modes.
3
4
## Capabilities
5
6
### Namespace
7
8
Simple helper class acting as a factory for QName instances, providing an easy way to work with namespaced XML elements and attributes.
9
10
```groovy { .api }
11
/**
12
* Default constructor for empty namespace
13
*/
14
Namespace()
15
16
/**
17
* Constructor with namespace URI
18
* @param uri - Namespace URI
19
*/
20
Namespace(String uri)
21
22
/**
23
* Constructor with URI and prefix
24
* @param uri - Namespace URI
25
* @param prefix - Namespace prefix
26
*/
27
Namespace(String uri, String prefix)
28
29
/**
30
* Create QName for local name in this namespace
31
* @param localName - Local name for the QName
32
* @return QName with namespace URI and local name
33
*/
34
QName get(String localName)
35
36
/**
37
* Get namespace prefix
38
* @return Namespace prefix string
39
*/
40
String getPrefix()
41
42
/**
43
* Get namespace URI
44
* @return Namespace URI string
45
*/
46
String getUri()
47
```
48
49
**Usage Examples:**
50
51
```groovy
52
import groovy.xml.Namespace
53
import groovy.namespace.QName
54
55
// Create namespaces
56
def xhtml = new Namespace("http://www.w3.org/1999/xhtml", "html")
57
def atom = new Namespace("http://www.w3.org/2005/Atom")
58
def empty = new Namespace()
59
60
// Create QNames
61
QName htmlDiv = xhtml.div // QName with XHTML namespace
62
QName atomEntry = atom.entry // QName with Atom namespace
63
QName plainElement = empty.test // QName with no namespace
64
65
// Access namespace properties
66
println xhtml.getUri() // "http://www.w3.org/1999/xhtml"
67
println xhtml.getPrefix() // "html"
68
println atom.getUri() // "http://www.w3.org/2005/Atom"
69
println atom.getPrefix() // null (no prefix specified)
70
71
// Use in XML building
72
def builder = new MarkupBuilder()
73
builder."${xhtml.html}"("xmlns:html": xhtml.getUri()) {
74
"${xhtml.head}" {
75
"${xhtml.title}"("Sample XHTML")
76
}
77
"${xhtml.body}" {
78
"${xhtml.p}"("Hello, namespaced world!")
79
}
80
}
81
```
82
83
---
84
85
### NamespaceBuilder
86
87
Helper class for creating namespaces in GroovyMarkup builders, providing a fluent API for namespace declaration and usage.
88
89
```groovy { .api }
90
/**
91
* Constructor with parent builder
92
* @param builder - Parent BuilderSupport instance
93
*/
94
NamespaceBuilder(BuilderSupport builder)
95
96
/**
97
* Create namespace support with URI
98
* @param builder - Parent BuilderSupport instance
99
* @param uri - Namespace URI
100
* @return NamespaceBuilderSupport instance
101
*/
102
static NamespaceBuilderSupport newInstance(BuilderSupport builder, String uri)
103
104
/**
105
* Create namespace support with default settings
106
* @param builder - Parent BuilderSupport instance
107
* @return NamespaceBuilderSupport instance
108
*/
109
static NamespaceBuilderSupport newInstance(BuilderSupport builder)
110
111
/**
112
* Create namespace support with URI and prefix
113
* @param builder - Parent BuilderSupport instance
114
* @param uri - Namespace URI
115
* @param prefix - Namespace prefix
116
* @return NamespaceBuilderSupport instance
117
*/
118
static NamespaceBuilderSupport newInstance(BuilderSupport builder, String uri, String prefix)
119
120
/**
121
* Create namespace support with namespace map
122
* @param nsMap - Map of namespace declarations
123
* @param builder - Parent BuilderSupport instance
124
* @return NamespaceBuilderSupport instance
125
*/
126
static NamespaceBuilderSupport newInstance(Map nsMap, BuilderSupport builder)
127
128
/**
129
* Create namespace for URI
130
* @param uri - Namespace URI
131
* @return NamespaceBuilderSupport for the namespace
132
*/
133
NamespaceBuilderSupport namespace(String uri)
134
135
/**
136
* Create namespace with URI and prefix
137
* @param uri - Namespace URI
138
* @param prefix - Namespace prefix
139
* @return NamespaceBuilderSupport for the namespace
140
*/
141
NamespaceBuilderSupport namespace(String uri, String prefix)
142
143
/**
144
* Declare multiple namespaces
145
* @param ns - Map of prefix to URI mappings
146
* @return NamespaceBuilderSupport with declared namespaces
147
*/
148
NamespaceBuilderSupport declareNamespace(Map ns)
149
```
150
151
---
152
153
### NamespaceBuilderSupport
154
155
Helper class extending BuilderSupport for creating namespaced GroovyMarkup with comprehensive namespace management.
156
157
```groovy { .api }
158
/**
159
* Constructor with parent builder
160
* @param builder - Parent BuilderSupport instance
161
*/
162
NamespaceBuilderSupport(BuilderSupport builder)
163
164
/**
165
* Constructor with builder and namespace URI
166
* @param builder - Parent BuilderSupport instance
167
* @param uri - Default namespace URI
168
*/
169
NamespaceBuilderSupport(BuilderSupport builder, String uri)
170
171
/**
172
* Constructor with builder, URI, and prefix
173
* @param builder - Parent BuilderSupport instance
174
* @param uri - Default namespace URI
175
* @param prefix - Default namespace prefix
176
*/
177
NamespaceBuilderSupport(BuilderSupport builder, String uri, String prefix)
178
179
/**
180
* Constructor with full configuration
181
* @param builder - Parent BuilderSupport instance
182
* @param uri - Default namespace URI
183
* @param prefix - Default namespace prefix
184
* @param autoPrefix - Automatically generate prefixes
185
*/
186
NamespaceBuilderSupport(BuilderSupport builder, String uri, String prefix, boolean autoPrefix)
187
188
/**
189
* Constructor with namespace map
190
* @param builder - Parent BuilderSupport instance
191
* @param nsMap - Map of namespace declarations
192
*/
193
NamespaceBuilderSupport(BuilderSupport builder, Map nsMap)
194
195
/**
196
* Create namespace support for URI
197
* @param namespaceURI - Namespace URI
198
* @return NamespaceBuilderSupport for the namespace
199
*/
200
NamespaceBuilderSupport namespace(String namespaceURI)
201
202
/**
203
* Create namespace support with URI and prefix
204
* @param namespaceURI - Namespace URI
205
* @param prefix - Namespace prefix
206
* @return NamespaceBuilderSupport for the namespace
207
*/
208
NamespaceBuilderSupport namespace(String namespaceURI, String prefix)
209
210
/**
211
* Declare multiple namespaces
212
* @param nsMap - Map of namespace declarations
213
* @return NamespaceBuilderSupport with declared namespaces
214
*/
215
NamespaceBuilderSupport declareNamespace(Map nsMap)
216
```
217
218
**Usage Examples:**
219
220
```groovy
221
import groovy.xml.*
222
223
// Basic namespace usage with MarkupBuilder
224
def writer = new StringWriter()
225
def xml = new MarkupBuilder(writer)
226
227
def ns = new NamespaceBuilder(xml)
228
def xhtml = ns.namespace("http://www.w3.org/1999/xhtml", "html")
229
def atom = ns.namespace("http://www.w3.org/2005/Atom")
230
231
// Build namespaced XML
232
xhtml.html {
233
xhtml.head {
234
xhtml.title("Mixed Namespace Document")
235
}
236
xhtml.body {
237
xhtml.h1("Blog Entries")
238
atom.feed {
239
atom.title("My Blog")
240
atom.entry {
241
atom.title("First Post")
242
atom.content("Hello World!")
243
}
244
}
245
}
246
}
247
248
println writer.toString()
249
250
// Using static factory methods
251
def builder = new MarkupBuilder()
252
def nsSupport = NamespaceBuilder.newInstance(builder, "http://example.org/data", "data")
253
254
nsSupport.root {
255
item(id: "1", "First Item")
256
item(id: "2", "Second Item")
257
}
258
259
// Multiple namespace declarations
260
def multiNs = NamespaceBuilder.newInstance([
261
"soap": "http://schemas.xmlsoap.org/soap/envelope/",
262
"data": "http://example.org/data"
263
], builder)
264
265
multiNs."soap:Envelope" {
266
"soap:Header" {
267
"data:AuthToken"("secret123")
268
}
269
"soap:Body" {
270
"data:GetUserRequest" {
271
"data:UserId"("12345")
272
}
273
}
274
}
275
276
// Complex namespace example with StreamingMarkupBuilder
277
def streamBuilder = new StreamingMarkupBuilder()
278
def markup = streamBuilder.bind {
279
mkp.xmlDeclaration(version: "1.0", encoding: "UTF-8")
280
281
namespaces << [
282
"rss": "http://purl.org/rss/1.0/",
283
"content": "http://purl.org/rss/1.0/modules/content/",
284
"dc": "http://purl.org/dc/elements/1.1/"
285
]
286
287
"rss:RDF" {
288
"rss:channel"("rdf:about": "http://example.org/rss") {
289
"rss:title"("My RSS Feed")
290
"rss:description"("Sample RSS with namespaces")
291
"dc:creator"("John Doe")
292
}
293
294
"rss:item"("rdf:about": "http://example.org/item1") {
295
"rss:title"("First Article")
296
"rss:link"("http://example.org/article1")
297
"content:encoded" {
298
mkp.yieldUnescaped("<p>Article content with <strong>HTML</strong></p>")
299
}
300
"dc:date"("2023-01-01")
301
"dc:creator"("Jane Smith")
302
}
303
}
304
}
305
306
// DOM building with namespaces
307
def domBuilder = DOMBuilder.newInstance(false, true) // namespace aware
308
def nsBuilder = new NamespaceBuilder(domBuilder)
309
def mathml = nsBuilder.namespace("http://www.w3.org/1998/Math/MathML", "m")
310
311
def doc = mathml.math {
312
mathml.mrow {
313
mathml.mi("x")
314
mathml.mo("+")
315
mathml.mi("y")
316
mathml.mo("=")
317
mathml.mn("5")
318
}
319
}
320
321
// Working with existing namespace declarations
322
def existingXml = '''
323
<soap:Envelope
324
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
325
xmlns:web="http://www.webserviceX.NET/">
326
<soap:Body>
327
<web:GetWeather>
328
<web:CityName>London</web:CityName>
329
</web:GetWeather>
330
</soap:Body>
331
</soap:Envelope>
332
'''
333
334
// Parse with namespace awareness
335
def slurper = new XmlSlurper(false, true)
336
def parsed = slurper.parseText(existingXml)
337
338
// Access namespaced elements
339
println parsed.name() // "Envelope"
340
println parsed.Body.GetWeather.CityName.text() // "London"
341
342
// Declare namespaces for GPath access
343
def nsAwareParsed = parsed.declareNamespace([
344
"soap": "http://schemas.xmlsoap.org/soap/envelope/",
345
"web": "http://www.webserviceX.NET/"
346
])
347
348
// Use namespace-aware navigation (implementation-dependent)
349
```
350
351
---
352
353
### Advanced Namespace Patterns
354
355
#### Namespace-Aware Parsing Configuration
356
357
```groovy { .api }
358
// Configure parsers for namespace awareness
359
XmlParser parser = new XmlParser(
360
false, // validating
361
true // namespace aware
362
)
363
364
XmlSlurper slurper = new XmlSlurper(
365
false, // validating
366
true // namespace aware
367
)
368
369
// Parse namespace-aware documents
370
def nsDoc = parser.parseText('''
371
<root xmlns="http://default.org"
372
xmlns:prefix="http://prefixed.org">
373
<child>default namespace</child>
374
<prefix:child>prefixed namespace</prefix:child>
375
</root>
376
''')
377
```
378
379
#### Working with QNames in Parsed Documents
380
381
```groovy
382
import groovy.namespace.QName
383
384
// When working with namespace-aware parsed documents
385
def element = nsDoc // from namespace-aware parsing
386
387
// Access namespace information
388
String namespaceURI = element.namespaceURI()
389
String localName = element.localName()
390
String prefix = element.prefix()
391
392
// Create QNames for comparison
393
def expectedQName = new QName("http://example.org", "element")
394
def actualQName = new QName(element.namespaceURI(), element.localName())
395
396
if (expectedQName == actualQName) {
397
println "Namespace match!"
398
}
399
```
400
401
#### Namespace Context in XPath
402
403
```groovy
404
import groovy.xml.dom.DOMCategory
405
import javax.xml.xpath.*
406
407
// Using namespaces with XPath in DOM processing
408
use(DOMCategory) {
409
def doc = // ... namespace-aware DOM document
410
411
// XPath with namespace context
412
def xpath = XPathFactory.newInstance().newXPath()
413
xpath.setNamespaceContext(new NamespaceContext() {
414
String getNamespaceURI(String prefix) {
415
switch(prefix) {
416
case "html": return "http://www.w3.org/1999/xhtml"
417
case "atom": return "http://www.w3.org/2005/Atom"
418
default: return null
419
}
420
}
421
422
String getPrefix(String namespaceURI) { /* implementation */ }
423
Iterator getPrefixes(String namespaceURI) { /* implementation */ }
424
})
425
426
// Use namespaced XPath
427
def result = xpath.evaluate("//html:p[@class='content']", doc)
428
def nodeSet = xpath.evaluate("//atom:entry/atom:title", doc, XPathConstants.NODESET)
429
}
430
```
431
432
**Complete Namespace Example:**
433
434
```groovy
435
import groovy.xml.*
436
437
// Create a complex namespaced document
438
def writer = new StringWriter()
439
def xml = new MarkupBuilder(writer)
440
441
// Set up namespaces
442
def ns = new NamespaceBuilder(xml)
443
def soap = ns.namespace("http://schemas.xmlsoap.org/soap/envelope/", "soap")
444
def wsse = ns.namespace("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse")
445
def app = ns.namespace("http://myapp.com/services", "app")
446
447
// Build SOAP envelope with multiple namespaces
448
soap.Envelope {
449
soap.Header {
450
wsse.Security {
451
wsse.UsernameToken {
452
wsse.Username("testuser")
453
wsse.Password("testpass")
454
}
455
}
456
}
457
soap.Body {
458
app.GetUserRequest {
459
app.UserId("12345")
460
app.IncludeDetails("true")
461
}
462
}
463
}
464
465
def soapXml = writer.toString()
466
println soapXml
467
468
// Parse and process the namespaced XML
469
def slurper = new XmlSlurper(false, true)
470
def parsed = slurper.parseText(soapXml)
471
472
// Navigate using GPath (namespace-aware)
473
def userId = parsed.Body.GetUserRequest.UserId.text()
474
def username = parsed.Header.Security.UsernameToken.Username.text()
475
476
println "User ID: $userId"
477
println "Username: $username"
478
```