LibXML2正在剥离属性内的新行



我在一个iOS应用程序中工作,该应用程序使用libXML2读取从后端系统检索的XML。我有以下XML,它是一个更大的XML文档的一部分:

<properties uiValue="This is a multiline description with text that should wrap but should also preserve any whitespace:                         like this whitespace.
And preserve newlines.
espace:~` !@#$%^&amp;*()_+=-&lt;&gt;/  " name="desc">
            <values value="This is a multiline description with text that should wrap but should also preserve any whitespace:                         like this whitespace.
And preserve newlines.
espace:~` !@#$%^&amp;*()_+=-&lt;&gt;/  "/>
</properties>

总的来说,文档的解析似乎还可以。我的问题是换行符没有被处理,所以当我读取属性值时,结果是:

This is a multiline description with text that should wrap but should also preserve any whitespace:                         like this whitespace.    And preserve newlines.    espace:~` !@#$%^&amp;*()_+=-&lt;&gt;/  

有什么办法可以保留这些新线路吗?如果我直接从服务器打印出响应XML,那么新行就会保留下来。不过,当我进行解析时,新行被去掉了。更为复杂的是,这是我试图修复的一些第三方代码,而且我还没有真正使用过那么多libXML2。相关代码(我相信)是:

NSLog(@"Response:n%@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
xmlDocPtr doc = xmlReadMemory([data bytes], [data length], NULL, NULL, XML_PARSE_COMPACT | XML_PARSE_NOBLANKS);
xmlNodePtr cur = ....;
xmlChar *attrValue = xmlGetProp(cur, (const xmlChar *) "uiValue");
NSString *attrString = [NSString stringWithCString:(char*)attrValue encoding:NSUTF8StringEncoding];

我已经尝试去掉XML_PARSE_COMPACT和XML_PARSE_NOBLANKS选项,但这并没有起到任何作用(这不是我所期望的,我相信它们只会影响节点)。

XML解析器不能也不会在属性中保留换行符。来自规格:

在将属性的值传递给应用程序或检查有效性后,XML处理器必须规范化属性值:

  • 如2.11行尾处理中所述,所有换行符都必须在#xA的输入上进行规范化,因此该算法的其余部分对以这种方式规范化的文本进行操作

  • 对于空白字符(#x0,#xD,#xA,#x9),将空白字符( )附加到归一化值

库在解析时执行这种规范化,因此换行符消失了。可以使用数字实体引用将换行符转义为&#xA;,但通常如果需要依赖换行符,则会使用元素值。

<properties uiValue="This is a multiline description with text that should wrap but &#xA;should also preserve any whitespace:                         like this whitespace.&#xA;&#xA;    And preserve newlines.&#xA;&#xA;    espace:~` !@#$%^&amp;*()_+=&#xA;&lt;&gt;/  ">
    <value>This is a multiline description with text that should wrap but should also preserve any whitespace:                         like this whitespace.
And preserve newlines.
espace:~` !@#$%^&amp;*()_+=-&lt;&gt;/  "</value>
</properties>

最新更新