4

我需要以 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>

是否可以生成来自 a 的上述 xml NSDictionary

谢谢!

4

4 回答 4

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]

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

iPhone 应用程序的 XML 序列化库

但是,如果您要做的只是创建一个服务器端可以识别的单一、稳定的格式,并且您没有大量的实体要转换,那么您自己的工作可能会更少。

于 2012-11-05T19:05:49.360 回答
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]];
    }
}
于 2015-12-09T21:43:51.087 回答
2

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

- (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];
于 2015-02-25T00:08:24.680 回答
0

从@RemembranceNN 前面获取答案并将其转换为 Swift。

extension Dictionary {
    func getXML(withStartElement startElement: String) -> String {
        (self as NSDictionary).getXML(withStartElement: "message")
    }
}

extension NSDictionary {
    func getXML(withStartElement startElement: String, addLeafChildAsAttributes attrFlag: Bool, dontCreateNameSpaceChilds nsFlag: Bool) -> String {
        var string = ""
        var startTag = "<\(startElement)"
        var tagValue = ""
    
        for (key, value) in self {
            if let arr = value as? NSArray {
                for item in arr {
                    if let itemDict = item as? NSDictionary {
                        tagValue.append(itemDict.getXML(withStartElement: "\(key)", addLeafChildAsAttributes: attrFlag, dontCreateNameSpaceChilds: nsFlag))
                    } else {
                        tagValue.append("<\(key)>")
                        tagValue.append("\(item)")
                        tagValue.append("</\(key)>")
                    }
                }
            } else if let nestedDict = value as? NSDictionary {
                tagValue.append(nestedDict.getXML(withStartElement: "\(key)", addLeafChildAsAttributes: attrFlag, dontCreateNameSpaceChilds: nsFlag))
            } else {
                if attrFlag || (nsFlag && "\(key)" == "xmlns") {
                    startTag.append(" \(key)=\"\(value)\"")
                }
                if !nsFlag || "\(key)" != "xmlns" {
                    tagValue.append("<\(key)>")
                    tagValue.append("\(value)")
                    tagValue.append("</\(key)>")
                }
            }
        }
        startTag.append(">")
        string.append(startTag)
        string.append(tagValue)
        string.append("</\(startElement)>")
        return string
    }
}
于 2022-01-14T14:08:35.540 回答