在iOS中解析多个属性值

时间:2013-10-10 07:31:20

标签: iphone ios ipad

我正在开发一个应用程序和  我想解析xml但是什么时候 它以多种属性的方式出现 那么你将如何使用nsxmlparser

来做到这一点
 <?xml version="1.0" encoding='utf-8' ?>
<Responses Id='7465'>
<Response RequestID="101" FunctionStatus="0" Message="OK"/>

<Result>

<PrimaryID>
<Item ID="1" Text="Aadhar Card"/>
<Item ID="2" Text="Voters ID"/>
<Item ID="3" Text="Driving Licence"/>
<Item ID="4" Text="PAN Card"/>
<Item ID="5" Text="Passport"/>
</PrimaryID>

<Sex>
<Item ID="1" Text="Male"/>
<Item ID="2" Text="Female"/>
</Sex>

<Title>
<Item ID="1" Text="Mr"/>
<Item ID="2" Text="Ms"/>
<Item ID="3" Text="Mrs"/>
</Title>
</Result>

</Responses>

1 个答案:

答案 0 :(得分:0)

使用XMLReader,您可以在这样的字典中获取它:

资源包中的

file.xml:

- (void)dataFromXML
{
    // Error
    NSError *error = nil;

    // Request
    NSMutableDictionary *xmlDic = nil;
    NSData *xmlData = nil;

    // Get XML
    xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"file" ofType:@"xml"]];

    // Parse the XML Data into a NSDictionary
    xmlDic = [NSMutableDictionary dictionaryWithDictionary:[XMLReader dictionaryForXMLData:xmlData error:&error]];

    // Configure Dictionary
    xmlDic = [[[xmlDic objectForKey:@"Responses"] objectForKey:@"Response"] objectForKey:@"Result"];
    NSLog(@"%@", xmlDic);
}

网络上的file.xml:

- (void)dataWSFromXML
{
    // Error
    NSError *error = nil;

    // Request
    NSURLRequest *request = nil;
    NSURLResponse *response = nil;
    NSMutableDictionary *xmlDic = nil;
    NSData *xmlData = nil;

    // Get XML
    request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://yourXMLfile.xml"]];
    xmlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; // You can improve this request

    // Parse the XML Data into a NSDictionary
    xmlDic = [NSMutableDictionary dictionaryWithDictionary:[XMLReader dictionaryForXMLData:xmlData error:&error]];

    // Configure Dictionary
    xmlDic = [[[xmlDic objectForKey:@"Responses"] objectForKey:@"Response"] objectForKey:@"Result"];
    NSLog(@"%@", xmlDic);
}

但我改变了你的XML:

<?xml version="1.0" encoding="UTF-8"?>
<Responses Id='7465'>
    <Response RequestID="101" FunctionStatus="0" Message="OK">
        <Result>

            <PrimaryID>
                <Item ID="1" Text="Aadhar Card"/>
                <Item ID="2" Text="Voters ID"/>
                <Item ID="3" Text="Driving Licence"/>
                <Item ID="4" Text="PAN Card"/>
                <Item ID="5" Text="Passport"/>
            </PrimaryID>

            <Sex>
                <Item ID="1" Text="Male"/>
                <Item ID="2" Text="Female"/>
            </Sex>

            <Title>
                <Item ID="1" Text="Mr"/>
                <Item ID="2" Text="Ms"/>
                <Item ID="3" Text="Mrs"/>
            </Title>
        </Result>
    </Response>
</Responses>