【问题标题】:Problems with parsing an xml into objects in Objective C在 Objective C 中将 xml 解析为对象的问题
【发布时间】:2012-08-24 21:18:43
【问题描述】:

我有这个带有一些 id 的 XML,每个都有一个数据,我正在尝试解析所有 XML,所以最后我会得到一个像这样的对象:

A1Object[a1,a1,a1,a1]
A2Object[a2,a2,a2,a2]

问题是首先只解析 A1,A2...

xml:

<response>
    <tmm>
        <tm id="A1"><DocumentElement>
            <cell>
                <name>Tom</name>
                <lastName>LastNameTom</lastName>
            </cell>
            <cell>
                <name>Tom1</name>
                <lastName>LastNameTom1</lastName>
            </cell>
        </tm>
        <tm id="A2">
            <cell>
                <carType>5</carType>
                <catId>4545</carId>
            </cell>
            <cell>
                <carType>6</carType>
                <catId>565656</carId>
            </cell>
        </tm>
        <tm id="A3">...</tm>
    </tmm>
</response>

对于每个对象 (a1,a2...),我都有他与他的字段的交互

我正在尝试下一件事:

  if (xmlDocument != nil)
        {
            NSArray *nodes = [xmlDocument nodesForXPath:@"//cell" error: nil];
            if (nodes != nil)
            { 
                for (CXMLNode *node in nodes)
                {
                     A1 *a1Object = [[A1 alloc] init];

                    for (int i = 0; i < [node childCount]; i++)
                    {
                        CXMLNode *child = [node childAtIndex: i];
                        NSString *str = [child stringValue];
                        if ([[child name] isEqualToString: @"name"])
                        { 
                            a1Object.A1FacilityId = ([str length] > 0) ? str : nil;
                        }
                        if ([[child name] isEqualToString: @"lastName"])
                        { 
                            a1Object.A1FacilityStreetName = ([str length] > 0) ? str : nil;
                        }                      
                    }

                    [self.A1s addObject:a1Object];
                    [a1Object release];
                }            
            }
        }

我怎样才能改进它,所以最后我得到了这样的结果:

A1Object[a1,a1,a1,a1]
A2Object[a2,a2,a2,a2

【问题讨论】:

  • 我已经给了here解析xml文件的答案。请根据您的xml提要检查和修改或检查tutorial
  • 在开始元素中:currentObject:[attributeDict objectForKey:@"id"];并在 didEndElement 中根据当前对象分配给适当的数组。

标签: iphone objective-c xml xml-parsing


【解决方案1】:

您可以使用 TBXML 来解析 XML。

http://tbxml.co.uk/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多