From 377ae43873da106296a5b0965cef6dc8523fbc3d Mon Sep 17 00:00:00 2001 From: Vasiliy Anisimov Date: Sat, 18 Apr 2020 20:25:26 +0300 Subject: [PATCH] [#237] Added logic to eval xpath for node relative to this node + added test to check that --- Sources/Kanna/libxmlHTMLDocument.swift | 11 ++++++++++- Tests/KannaTests/KannaHTMLTests.swift | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Sources/Kanna/libxmlHTMLDocument.swift b/Sources/Kanna/libxmlHTMLDocument.swift index 285c444..4a19613 100755 --- a/Sources/Kanna/libxmlHTMLDocument.swift +++ b/Sources/Kanna/libxmlHTMLDocument.swift @@ -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) @@ -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] { diff --git a/Tests/KannaTests/KannaHTMLTests.swift b/Tests/KannaTests/KannaHTMLTests.swift index 2c6dd16..c0ce5a2 100755 --- a/Tests/KannaTests/KannaHTMLTests.swift +++ b/Tests/KannaTests/KannaHTMLTests.swift @@ -202,6 +202,30 @@ class KannaHTMLTests: XCTestCase { XCTFail("Abnormal test data") } } + + func testInnerXpath() { + let input = """ + + + test title + + +

test header 1

+

test header 2

+ + + """ + 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 {