diff --git a/tinyxml2.cpp b/tinyxml2.cpp index 5e5b93d..96ec1bf 100644 --- a/tinyxml2.cpp +++ b/tinyxml2.cpp @@ -1074,6 +1074,17 @@ const XMLAttribute* XMLElement::FindAttribute( const char* name ) const } +const char* XMLElement::Attribute( const char* name, const char* value ) const +{ + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) + return 0; + if ( !value || XMLUtil::StringEqual( a->Value(), value )) + return a->Value(); + return 0; +} + + const char* XMLElement::GetText() const { if ( FirstChild() && FirstChild()->ToText() ) { diff --git a/tinyxml2.h b/tinyxml2.h index 6f3828c..e96e471 100644 --- a/tinyxml2.h +++ b/tinyxml2.h @@ -845,8 +845,23 @@ public: /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. + + 'value' is normally null. However, if specified, the attribute + will only be returned if the 'name' and 'value' match. This + allow you to write code: + + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim + + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim */ - const char* Attribute( const char* name ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return 0; return a->Value(); } + const char* Attribute( const char* name, const char* value=0 ) const; /** Given an attribute name, IntAttribute() returns the value of the attribute interpreted as an integer. 0 will be diff --git a/xmltest.cpp b/xmltest.cpp index 93b5599..20e3fa9 100644 --- a/xmltest.cpp +++ b/xmltest.cpp @@ -319,6 +319,7 @@ int main( int /*argc*/, const char ** /*argv*/ ) ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); + XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" ); XMLTest( "Attribute round trip. c-string.", "strValue", cStr ); XMLTest( "Attribute round trip. int.", 1, iVal ); XMLTest( "Attribute round trip. double.", -1, (int)dVal );