Function Tag.expectTagAttribute

Lookup a child tag and attribute by name, and retrieve a value of type T from it. Throws 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 expectTag().expectAttribute().

Prototype

T expectTagAttribute(T)(
  string fullTagName,
  string fullAttributeName
)
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"  // expectTagAttribute considers this to override the first foo
	
	bar X="hi"
	bar X=379  // expectTagAttribute considers this to override the first bar
`);
assert( root.expectTagAttribute!int("foo", "X") == 3 );
assert( root.expectTagAttribute!string("foo", "X") == "c" );

// The last "bar" tag doesn't have an int attribute named "X" (only the first "bar" tag does)
// If you'd rather receive a default value than an exception, use `getAttribute` instead.
assertThrown!AttributeNotFoundException( root.expectTagAttribute!string("bar", "X") );

// Tag not found
assertThrown!TagNotFoundException( root.expectTagAttribute!int("doesnt-exist", "X") );

// 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  // expectTagAttribute considers this to override the first bar
`);
assert( root.expectTagAttribute!int("ns1:foo", "X") == 3  );
assert( root.expectTagAttribute!int("*:foo",   "X") == 33 ); // Search all namespaces

assert( root.expectTagAttribute!string("ns1:foo", "X") == "c"  );
assert( root.expectTagAttribute!string("*:foo",   "X") == "cc" ); // Search all namespaces

// bar's attribute X is't in the default namespace
assertThrown!AttributeNotFoundException( root.expectTagAttribute!int("*:bar", "X") );

// The last "bar" tag's "attrNS:X" attribute doesn't have a string (only the first "bar" tag does)
assertThrown!AttributeNotFoundException( root.expectTagAttribute!string("*:bar", "attrNS:X") );

// Tag's namespace not found
assertThrown!TagNotFoundException( root.expectTagAttribute!int("doesnt-exist:bar", "attrNS:X") );

Authors

Copyright

License