将NSDictionary转换为XML

时间:2012-10-11 10:56:18

标签: ios xml nsdictionary

我需要以XML格式发布数据。服务器接受特定的xml格式。我不想手工编写xml,我想要做的是创建一个NSMutableDictionary填充它并从NSMutableDictionary转换它XML。

我用这个:

[NSPropertyListSerialization dataWithPropertyList:data format:NSPropertyListXMLFormat_v1_0 options:0

样本返回是:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">
<dict>
<key>email</key>
<string>me@n.net</string>
<key>invoice_date</key>
<string>2012-10-11T10:35:09Z</string>
<key>invoice_lines</key>
<array>
    <dict>
        <key>product_id</key>
        <integer>1021493</integer>
        <key>quantity</key>
        <real>1</real>
        <key>retail_price</key>
        <real>110</real>
    </dict>
</array>
<key>payments</key>
<array>
    <dict>
        <key>amount</key>
        <real>288.5</real>
    </dict>
    <dict>
        <key>payment_type_id</key>
        <integer>1</integer>
    </dict>
</array>

上述格式无法从服务器读取。

服务器需要像这样的xml提要。

  <invoice>
      <invoice_date>2012-10-11T10:35:09Z</invoice_date>
      <email>me@n.net</email>
        <invoice_lines type="array">
         <invoice_line>
       <product_id>1021505</product_id>
       <quantity>1</quantity>
       <retail_price>45</retail_price>
     </invoice_line>
  </invoice_lines>
  <payments type="array">
    <payment>
      <amount>288.5</amount>
     </payment>
  </payments>

</invoice>

是否可以从NSDictionary生成上述xml?

谢谢!

3 个答案:

答案 0 :(得分:4)

简短的回答是:不,在Cocoa库中没有内置的能力。

因为你正在编写而不是解析,并且可能处理有限的可能标签,输出XML的代码实际上并不复杂。它应该只是Invoice对象中的一个简单方法,如:

- (NSString*) postStringInXMLFormat
{
    NSMutableString* returnValue = [[NSMutableString alloc] init];
    if([self email])
    {
        [returnValue appendString:@"<email>"];
        [returnValue appendString:[self email]];
        [returnValue appendString:@"</email>"];
    }
    if([self invoice_date])
    ...

等等。在结束时返回

[NSString stringWithString:returnValue]

有很多第三方项目试图概括这个过程;其中有几个列在这个答案中:

Xml serialization library for iPhone Apps

但是,如果您要做的就是创建一个服务器端将识别的单一稳定格式,并且您没有可转换的实体数量,那么滚动自己的实体可能就不那么重要了。 / p>

答案 1 :(得分:3)

这是一种将字典转换为XML字符串的递归方法。它处理字典,数组和字符串。字典键是XML标记,字典对象用作树中的值或子项。在数组的情况下,数组中的每个元素都放在具有相同标记的相同子级别上。

- (NSString*)ConvertDictionarytoXML:(NSDictionary*)dictionary  withStartElement:(NSString*)startElement{
    NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];
    [xml appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"];
    [xml appendString:[NSString stringWithFormat:@"<%@>",startElement]];
    [self convertNode:dictionary withString:xml andTag:nil];
    [xml appendString:[NSString stringWithFormat:@"</%@>",startElement]];
    NSString *finalXML=[xml stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    NSLog(@"%@",xml);
    return finalXML;
}

- (void)convertNode:(id)node withString:(NSMutableString *)xml andTag:(NSString *)tag{
    if ([node isKindOfClass:[NSDictionary class]] && !tag) {
    NSArray *keys = [node allKeys];
    for (NSString *key in keys) {
        [self convertNode:[node objectForKey:key] withString:xml andTag:key];
    }
    }else if ([node isKindOfClass:[NSArray class]]) {
        for (id value in node) {
             [self convertNode:value withString:xml andTag:tag];
        }
    }else {
        [xml appendString:[NSString stringWithFormat:@"<%@>", tag]];
        if ([node isKindOfClass:[NSString class]]) {
        [xml appendString:node];
        }else if ([node isKindOfClass:[NSDictionary class]]) {
            [self convertNode:node withString:xml andTag:nil];
        }
        [xml appendString:[NSString stringWithFormat:@"</%@>", tag]];
    }
}

答案 2 :(得分:1)

如果您不使用库或需要额外的自定义:

- (NSString*)convertDictionaryToXML:(NSDictionary*)dictionary withStartElement:(NSString*)startElement
{
    return [self convertDictionaryToXML:dictionary withStartElement:startElement isFirstElement:YES];
}

- (NSString*)convertDictionaryToXML:(NSDictionary*)dictionary withStartElement:(NSString*)startElement isFirstElement:(BOOL) isFirstElement
{
    NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];
    NSArray *arr = [dictionary allKeys];
    if (isFirstElement)
    {
        [xml appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"];
    }
    [xml appendString:[NSString stringWithFormat:@"<%@>\n", startElement]];
    for(int i=0; i < [arr count]; i++)
    {
        NSString *nodeName = [arr objectAtIndex:i];
        id nodeValue = [dictionary objectForKey:nodeName];
        if([nodeValue isKindOfClass:[NSArray class]])
        {
            if([nodeValue count]>0)
            {
                for(int j=0;j<[nodeValue count];j++)
                {
                    id value = [nodeValue objectAtIndex:j];
                    if([value isKindOfClass:[NSDictionary class]])
                    {
                        [xml appendString:[self convertDictionaryToXML:value withStartElement:nodeName isFirstElement:NO]];
                    }
                }
            }
        }
        else if([nodeValue isKindOfClass:[NSDictionary class]])
        {
            [xml appendString:[self convertDictionaryToXML:nodeValue withStartElement:nodeName isFirstElement:NO]];
        }
        else
        {
            if([nodeValue length]>0){
                [xml appendString:[NSString stringWithFormat:@"<%@>",nodeName]];
                [xml appendString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:nodeName]]];
                [xml appendString:[NSString stringWithFormat:@"</%@>\n",nodeName]];
            }
        }
    }

    [xml appendString:[NSString stringWithFormat:@"</%@>\n",startElement]];

    NSString *finalxml=[xml stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];

    return finalxml;
}

并将其称为:

NSString *xmlString = [self convertDictionaryToXML:data withStartElement:startElementName];