Просмотр исходного кода

Added the improved attribute query

Lee Thomason 14 лет назад
Родитель
Сommit
8ba7f7d69b
3 измененных файлов с 28 добавлено и 1 удалено
  1. 11 0
      tinyxml2.cpp
  2. 16 1
      tinyxml2.h
  3. 1 0
      xmltest.cpp

+ 11 - 0
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() ) {

+ 16 - 1
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

+ 1 - 0
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 );