Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/Kanna/Kanna.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ XMLElement
*/
public protocol XMLElement: SearchableNode {
var parent: XMLElement? { get set }
var attributes: [String: String?] { get }
subscript(attr: String) -> String? { get set }

func addPrevSibling(_ node: XMLElement)
Expand Down
19 changes: 19 additions & 0 deletions Sources/Kanna/libxmlHTMLNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,25 @@ final class libxmlHTMLNode: XMLElement {
}
}

var attributes: [String : String?] {
var result: [String: String?] = [:]
var attribute = nodePtr.pointee.properties

while let attr = attribute {
let mem = attr.pointee
let prefix = mem.ns.flatMap { $0.pointee.prefix.string }
let attributeName = [prefix, mem.name.string].compactMap { $0 }.joined(separator: ":")

if let children = mem.children {
result[attributeName] = libxmlGetNodeContent(children)
}

attribute = attr.pointee.next
}

return result
}

init(document: XMLDocument?, docPtr: xmlDocPtr) throws {
self.weakDocument = document
self.docPtr = docPtr
Expand Down
12 changes: 12 additions & 0 deletions Tests/KannaTests/KannaTutorialsTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,18 @@ class KannaTutorialsTests: XCTestCase {

XCTAssert(doc.body?.toHTML == TestModifyHTML)
}

func testListAttributes() throws {
let html = """
<body>
<h2 class="show-title" data-hello="world">Three's Company</h2>
</body>
"""

let document = try HTML(html: html, encoding: .utf8)
let h2 = document.at_css("h2")!
XCTAssertEqual(["class": "show-title", "data-hello": "world"], h2.attributes)
}
}

extension KannaTutorialsTests {
Expand Down