Skip to content

Commit

Permalink
Fixed #32 innerHTML causes EXC_BAD_ACCESS
Browse files Browse the repository at this point in the history
  • Loading branch information
tid-kijyun committed Sep 3, 2015
1 parent c50ef52 commit 69018cf
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 15 deletions.
21 changes: 6 additions & 15 deletions Source/libxml/libxmlHTMLNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,12 @@ internal final class libxmlHTMLNode: XMLElement {
}

var innerHTML: String? {
var html: String = ""
html += libxmlGetNodeText(nodePtr.memory.children) ?? ""
html += self.xpath(".//*").first?.toHTML ?? ""
html += libxmlGetNodeText(xmlGetLastChild(nodePtr)) ?? ""
return html
if let html = self.toHTML {
let inner = html.stringByReplacingOccurrencesOfString("</.*>$", withString: "", options: .RegularExpressionSearch, range: nil)
.stringByReplacingOccurrencesOfString("^<.*>", withString: "", options: .RegularExpressionSearch, range: nil)
return inner
}
return nil
}

var className: String? {
Expand Down Expand Up @@ -162,16 +163,6 @@ internal final class libxmlHTMLNode: XMLElement {
}
}

private func libxmlGetNodeText(nodePtr: xmlNodePtr) -> String? {
if nodePtr != nil {
let type = nodePtr.memory.type
if type.value == XML_TEXT_NODE.value {
return libxmlGetNodeText(nodePtr)
}
}
return nil
}

private func libxmlGetNodeContent(nodePtr: xmlNodePtr) -> String? {
let content = xmlNodeGetContent(nodePtr)
if let result = String.fromCString(UnsafePointer(content)) {
Expand Down
11 changes: 11 additions & 0 deletions Tests/KannaTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,15 @@ class KannaTests: XCTestCase {
XCTAssert(false, "File not found. name: (\(filename))")
}
}

func testInnerHTML() {
let filename = "test_HTML4"
if let path = NSBundle(forClass:self.classForCoder).pathForResource(filename, ofType:"html"),
html = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String,
doc = HTML(html: html, encoding: NSUTF8StringEncoding) {

XCTAssert(doc.at_css("div#inner")!.innerHTML == "\n abc<div>def</div>hij<span>klmn</span>opq\n ")
XCTAssert(doc.at_css("#asd")!.innerHTML == "asd")
}
}
}
5 changes: 5 additions & 0 deletions Tests/test_HTML4.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,10 @@ <h2>header2</h2>
<tr><td>Swift-HTML-Parser</td><td>100</td></tr>
</tbody>
</table>

<div id="inner">
abc<div>def</div>hij<span>klmn</span>opq
</div>
<div id="asd">asd</div>
</body>
</html>

0 comments on commit 69018cf

Please sign in to comment.