gpt4 book ai didi

objective-c - LibXML2 剥离属性内的新行

转载 作者:行者123 更新时间:2023-11-29 11:16:48 26 4
gpt4 key购买 nike

我在一个 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 解析器不能也不会保留属性中的换行符。来自 the spec :

Before the value of an attribute is passed to the application or checked for validity, the XML processor MUST normalize the attribute value by applying the algorithm below:

  • All line breaks must have been normalized on input to #xA as described in 2.11 End-of-Line Handling, so the rest of this algorithm operates on text normalized in this way.
  • ...
  • For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value.

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

<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>

关于objective-c - LibXML2 剥离属性内的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com