Function Tag.getTagAttribute
Lookup a child tag and attribute 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 type T from given
the tag and attribute names. Only looks for immediate child tags of
this
, doesn't search recursively.
This is a shortcut for getTag()
, except if the tag isn't
found, then instead of a null reference error, it will return the requested
defaultValue
(or T.init by default).
Prototype
T getTagAttribute(T)(
string fullTagName,
string fullAttributeName,
T defaultValue = T .init
)
if (isValueType!T);
Example
import std .exception;
import sdlang .parser;
auto root = parseSource(`
foo X=1 X="a" X=2 X="b"
foo X=3 X="c" X=4 X="d" // getTagAttribute considers this to override the first foo
bar X="hi"
bar X=379 // getTagAttribute considers this to override the first bar
`);
assert( root .getTagAttribute!int("foo", "X") == 3 );
assert( root .getTagAttribute!string("foo", "X") == "c" );
// Value found, default value ignored.
assert( root .getTagAttribute!int("foo", "X", 999) == 3 );
// Tag not found
// If you'd prefer an exception, use `expectTagAttribute` instead of `getTagAttribute`
assert( root .getTagAttribute!int("doesnt-exist", "X", 999) == 999 );
assert( root .getTagAttribute!int("doesnt-exist", "X") == 0 );
assert( root .getTagAttribute!int("foo", "doesnt-exist", 999) == 999 );
assert( root .getTagAttribute!int("foo", "doesnt-exist") == 0 );
// The last "bar" tag doesn't have a string (only the first "bar" tag does)
assert( root .getTagAttribute!string("bar", "X", "Default") == "Default" );
assert( root .getTagAttribute!string("bar", "X") is null );
// Using namespaces:
root = parseSource(`
ns1:foo X=1 X="a" X=2 X="b"
ns1:foo X=3 X="c" X=4 X="d"
ns2:foo X=11 X="aa" X=22 X="bb"
ns2:foo X=33 X="cc" X=44 X="dd"
ns1:bar attrNS:X="hi"
ns1:bar attrNS:X=379 // getTagAttribute considers this to override the first bar
`);
assert( root .getTagAttribute!int("ns1:foo", "X") == 3 );
assert( root .getTagAttribute!int("*:foo", "X") == 33 ); // Search all namespaces
assert( root .getTagAttribute!string("ns1:foo", "X") == "c" );
assert( root .getTagAttribute!string("*:foo", "X") == "cc" ); // Search all namespaces
// bar's attribute X is't in the default namespace
assert( root .getTagAttribute!int("*:bar", "X", 999) == 999 );
assert( root .getTagAttribute!int("*:bar", "X") == 0 );
// The last "bar" tag's "attrNS:X" attribute doesn't have a string (only the first "bar" tag does)
assert( root .getTagAttribute!string("*:bar", "attrNS:X", "Default") == "Default" );
assert( root .getTagAttribute!string("*:bar", "attrNS:X") is null);