Skip to content

Commit

Permalink
Merge pull request #68 from mrotrifork/feature/escape-characters
Browse files Browse the repository at this point in the history
Escape characters when making XML document
  • Loading branch information
kazuhiro4949 authored Nov 23, 2021
2 parents fb74602 + f76bf48 commit d7a1d23
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
13 changes: 12 additions & 1 deletion SwiftyXMLParser/Accessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ extension XML {

private func traverse(_ element: Element) -> String {
let name = element.name
let text = element.text ?? ""
let text = escapeXMLCharacters(element.text ?? "")
let attrs = element.attributes.map { (k, v) in "\(k)=\"\(v)\"" }.joined(separator: " ")

let childDocs = element.childElements.reduce("", { (result, element) in
Expand All @@ -532,5 +532,16 @@ extension XML {
return "<\(name)\(attrs.isEmpty ? "" : " ")\(attrs)>\(text)\(childDocs)</\(name)>"
}
}

private func escapeXMLCharacters(_ string: String) -> String {
let charactersToEscape = [
["&", "&amp;"],
["<", "&lt;"],
[">", "&gt;"]
]
return charactersToEscape.reduce(string) {
$0.replacingOccurrences(of: $1[0], with: $1[1], options: .literal, range: nil)
}
}
}
}
13 changes: 13 additions & 0 deletions SwiftyXMLParserTests/ConverterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ class ConverterTests: XCTestCase {
}
}

func testMakeDocumentEscapingCharacters() throws {
let element = XML.Element(name: "name", text: "me&you", childElements: [
XML.Element(name: "child", text: "& < > &")
])
let converter = XML.Converter(XML.Accessor(element))

XCTAssertEqual(
try converter.makeDocument(),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><name>me&amp;you<child>&amp; &lt; &gt; &amp;</child></name>",
"escape characters when making xml document"
)
}

func testMakeDocumentWithoutAttributes() throws {
let element = XML.Element(name: "name")
let converter = XML.Converter(XML.Accessor(element))
Expand Down

0 comments on commit d7a1d23

Please sign in to comment.