Skip to content

Commit

Permalink
[#237] Added logic to eval xpath for node relative to this node + add…
Browse files Browse the repository at this point in the history
…ed test to check that
  • Loading branch information
anivaros committed Apr 18, 2020
1 parent 653a905 commit 377ae43
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
11 changes: 10 additions & 1 deletion Sources/Kanna/libxmlHTMLDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ struct XPath {
ctxt.pointee.node = node
}

guard let result = xmlXPathEvalExpression(xpath, ctxt) else { return .none }
guard let result = xmlXPathEvalExpression(adoptXpath(xpath), ctxt) else { return .none }
defer { xmlXPathFreeObject(result) }

return XPathObject(document: doc, docPtr: docPtr, object: result.pointee)
Expand All @@ -358,6 +358,15 @@ struct XPath {
}
return .none
}

private func adoptXpath(_ xpath: String) -> String {
guard !isRoot else { return xpath }
if xpath.hasPrefix("/") {
return "." + xpath
} else {
return xpath
}
}
}

private func getNamespaces(docPtr: xmlDocPtr?) -> [Namespace] {
Expand Down
24 changes: 24 additions & 0 deletions Tests/KannaTests/KannaHTMLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,30 @@ class KannaHTMLTests: XCTestCase {
XCTFail("Abnormal test data")
}
}

func testInnerXpath() {
let input = """
<html>
<head>
<title>test title</title>
</head>
<body>
<div id="1"><div><h1>test header 1</h1></div></div>
<div id="2"><div><h1>test header 2</h1></div></div>
</body>
</html>
"""
do {
let doc = try HTML(html: input, encoding: .utf8)
XCTAssertNil(doc.at_xpath("//head")?.at_xpath("//h1"))
XCTAssertNil(doc.at_xpath("//head")?.at_xpath("//body"))
XCTAssertNil(doc.at_xpath("//body")?.at_xpath("//title"))
XCTAssertEqual(doc.at_xpath("//body/div[@id='2']//h1")?.text, "test header 2")
XCTAssertEqual(doc.at_xpath("//body/div[@id='2']")?.at_xpath("//h1")?.text, "test header 2")
} catch {
XCTFail("Abnormal test data")
}
}
}

extension KannaHTMLTests {
Expand Down

0 comments on commit 377ae43

Please sign in to comment.