Function Tag.getAttribute
Lookup an attribute of this
tag by name, and retrieve a value of type T
from it. Returns a default value if not found.
Useful if you only expect one attribute of the given name and type.
Only looks for attributes of this
tag, it does not search child tags.
If you wish to search for a value in a child tag (for example, if this
current tag is a root tag), try getTagAttribute
.
If you expect multiple attributes by the same name and want to get them all,
use maybe
.attributes[string]
instead.
The attribute name can optionally include a namespace, as in
"namespace:name"
. Or, you can search all namespaces using "*:name"
.
(Note that unlike tags. attributes can't be anonymous - that's what
values are.) Wildcard searching is only supported for namespaces, not names.
Use maybe
.attributes[0]
if you don't care about the name.
If this tag has multiple attributes, the first attribute matching the requested name and type will be returned. Ie, Extra attributes in the tag are ignored.
You may provide a default value to be returned in case no attribute of
the requested name and type can be found. If you don't provide a default
value, T
will be used.
If you'd rather an exception be thrown when an attribute cannot be found,
use expectAttribute
instead.
Prototype
T getAttribute(T)(
string fullAttributeName,
T defaultValue = T .init
)
if (isValueType!T);
Example
import std .exception;
import std .math;
import sdlang .parser;
auto root = parseSource(`
foo z=0 X=1 X=true X=2 X=false
`);
auto foo = root .getTag("foo");
assert( foo .getAttribute!int("X") == 1 );
assert( foo .getAttribute!bool("X") == true );
// Value found, default value ignored.
assert( foo .getAttribute!int("X", 999) == 1 );
// Attribute name not found
// If you'd prefer an exception, use `expectValue` instead.
assert( foo .getAttribute!int("doesnt-exist", 999) == 999 );
assert( foo .getAttribute!int("doesnt-exist") == 0 );
// No strings found
assert( foo .getAttribute!string("X", "Default") == "Default" );
assert( foo .getAttribute!string("X") is null );
// No floats found
assert( foo .getAttribute!float("X", 99.9) .approxEqual(99.9) );
assert( foo .getAttribute!float("X") .isNaN() );
// Using namespaces:
root = parseSource(`
foo ns1:z=0 ns1:X=1 ns1:X=2 ns2:X=3 ns2:X=4
`);
foo = root .getTag("foo");
assert( foo .getAttribute!int("ns2:X") == 3 );
assert( foo .getAttribute!int("*:X") == 1 ); // Search all namespaces
// Namespace not found
assert( foo .getAttribute!int("doesnt-exist:X", 999) == 999 );
// No attribute X is in the default namespace
assert( foo .getAttribute!int("X", 999) == 999 );
// Attribute name not found
assert( foo .getAttribute!int("ns1:doesnt-exist", 999) == 999 );