2012-02-01 57 views
1

我正在使用libXML2读取从后端系统检索到的XML的iOS应用程序中工作。我有以下的XML,这是一个更大的XML文档的一部分:LibXML2剥离属性中的新行

<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:~` [email protected]#$%^&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:~` [email protected]#$%^&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:~` [email protected]#$%^&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的选择了,但这并没有帮助(不,我预期,我相信那些仅影响节点)。

回答

2

XML解析器不能也不会保留属性中的换行符。从the spec

  • 所有行:

    一个属性的值被传递到检查其有效性的应用或 之前,XML处理器必须通过应用下面的算法标准化属性 值如2.11行尾处理中所述,输入到#xA时必须对中断进行标准化,所以该算法的其余部分对以这种方式标准化的文本进行操作。

  • ...
  • 对于一个空白字符(#X20,#xD,#xA,#X9),添加一个空格字符(#X20)的标准值。

库执行此正常化,因为它的解析,所以换行了。您可以使用数字实体引用将您的换行符转义为&#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:~` [email protected]#$%^&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:~` [email protected]#$%^&amp;*()_+=-&lt;&gt;/ "</value> 
</properties>