TBXML解析属性名称的值

时间:2013-09-19 09:15:21

标签: iphone ios xml parsing tbxml

我有这个xml:

            <AccountsList>
               <Account 
            Cod="0000" 
            AccountNumber="12345" 
            AccountName="John" 
            AccountSecondName="Wilson" />

        </AccountsList>

为解析它,我使用

            [TBXML valueOfAttributeNamed:@"Cod" forElement:element]
            [TBXML valueOfAttributeNamed:@"AccountNumber" forElement:element]
            [TBXML valueOfAttributeNamed:@"AccountName" forElement:element]
            [TBXML valueOfAttributeNamed:@"AccountSecondName" forElement:element]

但是如果xml没有COD:

            <AccountsList>
               <Account 

            AccountNumber="12345" 
            AccountName="John" 
            AccountSecondName="Wilson" 
                        />
        </AccountsList>

我崩溃了!我如何检查存在

            [TBXML valueOfAttributeNamed:@"Cod" forElement:element]
是不是?

如果struct没有帮助:(

             if ([TBXML valueOfAttributeNamed:@"Cod" forElement:element])

总是返回TRUE

解决方案:

现在我尝试检查空字符串,这对我有帮助。

          if ([TBXML valueOfAttributeNamed:@"Cod" forElement:element] isEqualToString:@"")

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码检索属性值:

TBXMLAttribute * attribute = element->firstAttribute;

//Checking attribute is valid or not
while (attribute)
{
    //Here you can check the `Cod` attribute exist or not
    NSLog(@"%@->%@ = %@",[TBXML elementName:element],[TBXML attributeName:attribute], TBXML attributeValue:attribute]);

    // Next attribute
    attribute = attribute->next;
}