【问题标题】:Error! using CDATA in strings.xml resource Android错误!在 strings.xml 资源 Android 中使用 CDATA
【发布时间】:2013-02-02 08:29:30
【问题描述】:

我的 Android 项目中有一个字符串资源,我正在使用 CDATA 部分将我的字符串嵌入 XML:

<string name="ackng"><![CDATA[
    <html>
<body>
    <h1>Acknowledgements</h1> 
    <p>
        Senator  Paul  Wellstone's  book,  the  Conscience  of  a  Liberal:  Reclaiming  the
        compassionate agenda was an inspiration and an affirmation that you can be truthful
        and  honest  as  a  politician,  and  compassionate  and  people-centred  as  a  representative.
        And  as  President  Bill  Clinton  affirmed  as  he  addressed  the  joint  session  of  the
        National  Assembly  on  26th  August,  2000,  thus:
        “Every  nation  that  has  struggled  to  build  democracy  has  found  that  success
        depends on leaders  who believe government exists to  serve people, not the
        other  way  around.”
    </p>
    <p>
        Paul  Wellstone's  book  was  my  inspiration  for  the  launching  of  the  compassionate
        agenda  in  February  2002.  Clinton's  speech  affirmed  my  convictions  regarding  the
        sanctity of the democratic mandate to serve the people. I acknowledge the clarity of
        their  focus  and  the  inspiration  their  works  continue  to  provide.
    </p>
</body></html>]]></string>

但 eclispe 正在返回此错误:

[2013-02-18 00:11:05 - MyPA] C:\Users\Daniel\workspace\MyPA\res\values\strings.xml:191: error: Apostrophe not preceded by \ (in  <html>

【问题讨论】:

    标签: android cdata


    【解决方案1】:

    撇号 (') 必须使用 \ 进行转义。尝试在整个字符串内容中使用\' 而不是'

    此外,您需要在以下部分中使用\" 转义"

    “Every  nation  that  has  struggled  to  build  democracy  has  found  that  success
    depends on leaders  who believe government exists to  serve people, not the
    other  way  around.”
    

    【讨论】:

      【解决方案2】:

      String Formatting and Styling

      转义撇号和引号

      如果字符串中有撇号或引号,则必须对其进行转义或将整个字符串括在另一种类型的封闭引号中。例如,以下是一些有效和无效的刺痛:

      <string name="good_example">"This'll work"</string>
      <string name="good_example_2">This\'ll also work</string>
      <string name="bad_example">This doesn't work</string>
      <string name="bad_example_2">XML encodings don&apos;t work</string>
      

      看起来bad_example_2 描述了您的问题。最好的办法是模仿 good_example_2,按照 Raghav Sood 的建议,分别将 '" 替换为 \'\"

      【讨论】:

      • 我认为使用 来保存 html 代码可以使其免受撇号等问题的影响
      • @mister_dani,我的理解是 CDATA 部分会影响 XML 解析器从 XML 字符串派生文本节点的方式,但该文档表明 XML 文档处理器需要文本节点(解析后)使用与 XML 转义不同的特定转义约定。
      • @mister_dani 不,它不直观,但 CDATA 对撇号没有帮助,您还需要转义它。
      • @mister_dani,我想我们同意了。 CDATA 部分仅影响 XML 转义约定,而不影响使用此输入的 Eclipse 模块所需的转义约定。
      【解决方案3】:

      使用&amp;#39; 代替撇号。字符的效果是在HTML输出的情况下(我猜是html)相等。所以&amp;#39;会显示为'

      【讨论】:

      • 我不知道是谁投了反对票,但这个正确的...+1
      猜你喜欢
      • 2013-10-17
      • 2018-02-15
      • 2015-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多