开发者

How to parse .XML with special characters (GDataXML)

开发者 https://www.devze.com 2023-01-25 02:54 出处:网络
Here is my .XML: <table> <report field=\"FROZEN_BY\" /> <user name=\"Peter O\'Toole\" count=\"16\">

Here is my .XML:

<table>
  <report field="FROZEN_BY" />
  <user name="Peter O'Toole" count="16">
    <row>
      <QTY value="2" />
      <EXTENSION value="SLDASM" />
    </row>
    <row>
      &l开发者_如何学编程t;QTY value="3" />
      <EXTENSION value="SLDDRW" />
    </row>
    <row>
      <QTY value="3" />
      <EXTENSION value="SLDPRT" />
    </row>
    <row>
      <QTY value="8" />
      <EXTENSION value="ZIP" />
    </row>
  </user>
</table>

the problem I am having comes from this line of xcode:

NSString* xPath = @"/table/user[@name='Peter O'Toole']/row";

when the username contains any .XML special characters I get an error:

XPath error : Invalid predicate
/table/user[@name='Peter O'Toole']/row
                          ^
xmlXPathEval: evaluation failed

I expected this, but when I change the line to:

NSString* xPath = @"/table/user[@name='Peter O&amp;Toole']/row";

I no longer get the error, but I also don't get any results.

Any thoughts on this?


You're in an XPath expression in a string literal, not in XML, so &amp; isn't an escape at all (and even if it were, it would be & rather than '). You're literally matching name attributes with the value Peter O&amp;Toole, ie attributes that would be written in the XML as name="Peter O&amp;amp;Toole".

XPath string literals can use either type of quote, so this expression would work:

/table/user[@name="Peter O'Toole"]/row

Which, for inclusion in an Obj-C string literal would need the double-quotes escaping again:

NSString* xPath = @"/table/user[@name=\"Peter O'Toole\"]/row";

If you have both kinds of quote in a string you want to match, you've got more of an issue. XPath string literals do not have an escaping scheme so it's impossible to state a value with both " and ' in it. You have to do it by concatenating strings that have only one type of quote in. So for arbitrary strings it may be easier to manually iterate-and-compare than to use an XPath.

0

精彩评论

暂无评论...
验证码 换一张
取 消