TBXML XML格式

时间:2012-07-28 18:53:31

标签: iphone xml xcode tbxml

我已经知道TBXML如何在我的Xcode项目中解析它。但我坚持使用我不太清楚的XML结构。

这是XML结构:

    <CurDate Dates="27.07.2012" Date="07/27/2012">
    <Currency Kod="USD" CurrencyCode="USD">
    <Unit>1</Unit>
    <Name>AMERICA</Name>
    <CurrencyName>US DOLLAR</CurrencyName>
    <ForexBuying>1.81</ForexBuying>
    <ForexSelling>1.8187</ForexSelling>
    </Currency>
    </CurDate>

我想要这个XML结构的帮助。我的代码如下:

        TBXMLElement *elementName = [TBXML childElementNamed:@"Currency" parentElement:element];
        TBXMLElement *altinTemp = [TBXML childElementNamed:@"CurrencyName" parentElement:elementName];

这是我获取XML的CurrencyName的方法,但是我得到了一个错误。见代码:

    + (TBXMLElement*) childElementNamed:(NSString*)aName parentElement:(TBXMLElement*)aParentXMLElement{
TBXMLElement * xmlElement = aParentXMLElement->firstChild;
const char * name = [aName cStringUsingEncoding:NSUTF8StringEncoding];
while (xmlElement) {
    if (strlen(xmlElement->name) == strlen(name) && memcmp(xmlElement->name,name,strlen(name)) == 0) {
        return xmlElement;
    }
    xmlElement = xmlElement->nextSibling;
}
return nil;
}

这是我得到一个错误。错误是“线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x10)

任何回复对我都有好处!感谢。

1 个答案:

答案 0 :(得分:0)

我相信你想要这样的东西

NSError *error = nil;
TBXML* tbxml = [TBXML tbxmlWithXMLString:@"<CurDate Dates='27.07.2012' Date='07/27/2012'><Currency Kod='USD' CurrencyCode='USD'><Unit>1</Unit><Name>AMERICA</Name><CurrencyName>US DOLLAR</CurrencyName><ForexBuying>1.81</ForexBuying><ForexSelling>1.8187</ForexSelling></Currency></CurDate>" error:&error];

if (error) {
    NSLog(@"%@ %@", [error localizedDescription], [error userInfo]);
} else {
// If TBXML found a root node, process element and iterate all children
    if (tbxml.rootXMLElement){
        TBXMLElement *element = tbxml.rootXMLElement;

        if ([TBXML childElementNamed:@"Currency" parentElement:element]) {

            element = element->firstChild;

            do{
                TBXMLElement *altinTemp = [TBXML childElementNamed:@"CurrencyName" parentElement:element];
                NSString *currencyName = [TBXML textForElement:[TBXML childElementNamed:@"CurrencyName" parentElement:element]];
                NSLog(@"%@",currencyName);
            }while ((element = element->nextSibling));

            error = nil;
        } 
    }
}

的替代方案
childElementNamed: parentElement:

childElementNamed: parentElement: error:

这允许你处理nil节点(我认为你有)。错误:也可以添加到大多数TBXML类函数中,它会降低性能,因此最好只用于调试或节点/值可能存在或不存在的时候。