createAttrPrefix finds the name space prefix attribute to use for the given name space, defining a new prefix if necessary. It returns the prefix.
(url string)
| 335 | // createAttrPrefix finds the name space prefix attribute to use for the given name space, |
| 336 | // defining a new prefix if necessary. It returns the prefix. |
| 337 | func (p *printer) createAttrPrefix(url string) string { |
| 338 | if prefix := p.attrPrefix[url]; prefix != "" { |
| 339 | return prefix |
| 340 | } |
| 341 | |
| 342 | // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml" |
| 343 | // and must be referred to that way. |
| 344 | // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns", |
| 345 | // but users should not be trying to use that one directly - that's our job.) |
| 346 | if url == xmlURL { |
| 347 | return xmlPrefix |
| 348 | } |
| 349 | |
| 350 | // Need to define a new name space. |
| 351 | if p.attrPrefix == nil { |
| 352 | p.attrPrefix = make(map[string]string) |
| 353 | p.attrNS = make(map[string]string) |
| 354 | } |
| 355 | |
| 356 | // Pick a name. We try to use the final element of the path |
| 357 | // but fall back to _. |
| 358 | prefix := strings.TrimRight(url, "/") |
| 359 | if i := strings.LastIndex(prefix, "/"); i >= 0 { |
| 360 | prefix = prefix[i+1:] |
| 361 | } |
| 362 | if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { |
| 363 | prefix = "_" |
| 364 | } |
| 365 | // xmlanything is reserved and any variant of it regardless of |
| 366 | // case should be matched, so: |
| 367 | // (('X'|'x') ('M'|'m') ('L'|'l')) |
| 368 | // See Section 2.3 of https://www.w3.org/TR/REC-xml/ |
| 369 | if len(prefix) >= 3 && strings.EqualFold(prefix[:3], "xml") { |
| 370 | prefix = "_" + prefix |
| 371 | } |
| 372 | if p.attrNS[prefix] != "" { |
| 373 | // Name is taken. Find a better one. |
| 374 | for p.seq++; ; p.seq++ { |
| 375 | if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" { |
| 376 | prefix = id |
| 377 | break |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | p.attrPrefix[url] = prefix |
| 383 | p.attrNS[prefix] = url |
| 384 | |
| 385 | p.WriteString(`xmlns:`) |
| 386 | p.WriteString(prefix) |
| 387 | p.WriteString(`="`) |
| 388 | EscapeText(p, []byte(url)) |
| 389 | p.WriteString(`" `) |
| 390 | |
| 391 | p.prefixes = append(p.prefixes, prefix) |
| 392 | |
| 393 | return prefix |
| 394 | } |
no test coverage detected