0

我正在开发一个应用程序,我想解析 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>
4

1 回答 1

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>
于 2013-10-10T08:00:38.723 回答