【问题标题】:LibXML2 stripping new lines inside attributeLibXML2 剥离属性内的新行
【发布时间】:2012-02-01 19:20:48
【问题描述】:

我正在使用 libXML2 读取从后端系统检索到的 XML 的 iOS 应用程序。我有以下 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>

作为一个整体,文档似乎解析OK。我遇到的问题是换行符没有被处理,所以当我读取属性值时,结果是:

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 选项,但这没有帮助(不是我期望的,我相信这些只会影响节点)。

【问题讨论】:

    标签: objective-c ios xml libxml2


    【解决方案1】:

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

    在将属性的值传递给应用程序之前或 检查有效性,XML 处理器必须规范化属性 通过应用以下算法获得价值:

    • 所有换行符都必须按照 2.11 行尾处理中所述在输入到 #xA 时进行规范化,因此该算法的其余部分对以这种方式规范化的文本进行操作。
    • ...
    • 对于空格字符(#x20、#xD、#xA、#x9),将空格字符 (#x20) 附加到标准化值。

    库在解析时执行此规范化,因此换行符消失了。您可以使用数字实体引用将换行符转义为&amp;#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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      相关资源
      最近更新 更多