2012-02-01 62 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>