2011-08-21 41 views
0

我想解析一個XML文件使用NSXMLParser,但方法[parser columnNumber]返回一個錯誤的值。舉例來說,在我的.xml我:NSXMLParser列號是錯誤的

... 
<Test><something type="great"><lol>Joy</lol> // Three elements in the same line 
... 
</something> 
</Test> 

對於元素 「測試」,我得到了正確的路線:

<Test><something type="great"><lol>Joy</lol> 

但列號爲 「6」。 在同一行,我得到列號「22」爲元素「東西」:

"great"><lol>Joy</lol> 

這是一個預期的行爲?

+0

我在蘋果bug記者提交了一個錯誤,這似乎並不像預期的行爲。 – Donovan

回答

0

編輯。兩次頭痛之前,我仍然充滿希望。現在我認爲將文件重新格式化以避免像同一行中的元素這樣的奇怪事情並且執行一些空白字符清理會更好。但這很奇怪。什麼錯誤。


嗯,這很奇怪,但我仍然在寫一個答案。

我正在做一些測試,使用一個示例XML和一些從NSXML獲得的行/列號。

<?xml version="1.0"?> 
<catalog class="something"> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
... 

column, line 
OPEN/CLOS element 

等形式的日誌(我在智能調試漂亮的小白)

15, 2 (A) 
OPEN catalog 
12, 3 (B) 
OPEN book 
14, 4 
OPEN author 
CLOS author 
13, 5 
OPEN title 
CLOS title 
13, 6 
OPEN genre 
CLOS genre 
13, 7 
OPEN price 
CLOS price 
20, 8 
OPEN publish_date 
CLOS publish_date 
19, 9 
OPEN description 
CLOS description 
CLOS book 
... 

有一種永遠奏效一個公式,即:

columnPosition = columnNumber - length("<element>") 

例如,考慮第二行和日誌附近(A):

<catalog class="something"> 

我希望columnPosition等於0,其實:

len("<catalog class>") = 15 
0 = 15 - length("<catalog class>") 

注意NSXML的columnNumber仍然是15不管我在「class」標籤內部寫入,但是當我移除整個標籤時,它是9。用下面的一行:

<catalog> 

我希望columnPosition等於0,其實:

length("<catalog>") = 9 
0 = 9 - length("<catalog>") 

現在,考慮下面一行,在日誌(B):

<book id="bk101"> 

我期待columnNumber等於3。其實:

length("<book id>") = 9 
3 = 12 - length("<book id>") 

好吧,這很奇怪。我認爲這不是一個很好的解決方案,但至少它是有效的。我不能簡單地刪除字符串的開頭空格,因爲它沒有,如果有這樣一行:

<catalog class="something"><book id="bk101"> 

你覺得這個怎麼樣?我覺得挺有意思的,但是如果沒有別的辦法,我會檢查這個答案作爲接受的答案。我期待着你們的想法。


避免了簡潔和缺乏意志的正式證明。

+1

哇!偉大的觀察。我已經證實,這也是我發生的事情。 – arlomedia

0

爲什麼不在startElement方法中遞增等級並在endElement中遞減?這樣你跟蹤嵌套級別

+0

使用OP的答案中的「目錄」示例,作者,標題和流派元素都會觸發startElement方法,但您只想增加第一個的嵌套層次。有沒有辦法做到這一點,而不看parser.columnNumber? – arlomedia

+0

只有在找到指定的元素時,才必須在startelement方法增量中檢查元素名稱。特殊方法中減少相同的方式 – iosDeveloper