Skip to content

Instantly share code, notes, and snippets.

@erica
Last active March 11, 2017 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/07a182db4d2ee88359991b743c157d8e to your computer and use it in GitHub Desktop.
Save erica/07a182db4d2ee88359991b743c157d8e to your computer and use it in GitHub Desktop.
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>
Key: catalog
Value: [ ]
Key: book
Value: [ ]
Attributes: [id: bk101]
Key: author
Value: [Gambardella, Matthew]
Key: title
Value: [XML Developer's Guide]
Key: genre
Value: [Computer]
Key: price
Value: [44.95]
Key: publish_date
Value: [2000-10-01]
Key: description
Value: [An in-depth look at creating applications with XML.]
Key: book
Value: [ ]
Attributes: [id: bk102]
Key: author
Value: [Ralls, Kim]
Key: title
Value: [Midnight Rain]
Key: genre
Value: [Fantasy]
Key: price
Value: [5.95]
Key: publish_date
Value: [2000-12-16]
Key: description
Value: [A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.]
Key: book
Value: [ ]
Attributes: [id: bk103]
Key: author
Value: [Corets, Eva]
Key: title
Value: [Maeve Ascendant]
Key: genre
Value: [Fantasy]
Key: price
Value: [5.95]
Key: publish_date
Value: [2000-11-17]
Key: description
Value: [After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.]
Key: book
Value: [ ]
Attributes: [id: bk104]
Key: author
Value: [Corets, Eva]
Key: title
Value: [Oberon's Legacy]
Key: genre
Value: [Fantasy]
Key: price
Value: [5.95]
Key: publish_date
Value: [2001-03-10]
Key: description
Value: [In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.]
Key: book
Value: [ ]
Attributes: [id: bk105]
Key: author
Value: [Corets, Eva]
Key: title
Value: [The Sundered Grail]
Key: genre
Value: [Fantasy]
Key: price
Value: [5.95]
Key: publish_date
Value: [2001-09-10]
Key: description
Value: [The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.]
Key: book
Value: [ ]
Attributes: [id: bk106]
Key: author
Value: [Randall, Cynthia]
Key: title
Value: [Lover Birds]
Key: genre
Value: [Romance]
Key: price
Value: [4.95]
Key: publish_date
Value: [2000-09-02]
Key: description
Value: [When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.]
Key: book
Value: [ ]
Attributes: [id: bk107]
Key: author
Value: [Thurman, Paula]
Key: title
Value: [Splish Splash]
Key: genre
Value: [Romance]
Key: price
Value: [4.95]
Key: publish_date
Value: [2000-11-02]
Key: description
Value: [A deep sea diver finds true love twenty thousand leagues beneath the sea.]
Key: book
Value: [ ]
Attributes: [id: bk108]
Key: author
Value: [Knorr, Stefan]
Key: title
Value: [Creepy Crawlies]
Key: genre
Value: [Horror]
Key: price
Value: [4.95]
Key: publish_date
Value: [2000-12-06]
Key: description
Value: [An anthology of horror stories about roaches, centipedes, scorpions and other insects.]
Key: book
Value: [ ]
Attributes: [id: bk109]
Key: author
Value: [Kress, Peter]
Key: title
Value: [Paradox Lost]
Key: genre
Value: [Science Fiction]
Key: price
Value: [6.95]
Key: publish_date
Value: [2000-11-02]
Key: description
Value: [After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.]
Key: book
Value: [ ]
Attributes: [id: bk110]
Key: author
Value: [O'Brien, Tim]
Key: title
Value: [Microsoft .NET: The Programming Bible]
Key: genre
Value: [Computer]
Key: price
Value: [36.95]
Key: publish_date
Value: [2000-12-09]
Key: description
Value: [Microsoft's .NET initiative is explored in detail in this deep programmer's reference.]
Key: book
Value: [ ]
Attributes: [id: bk111]
Key: author
Value: [O'Brien, Tim]
Key: title
Value: [MSXML3: A Comprehensive Guide]
Key: genre
Value: [Computer]
Key: price
Value: [36.95]
Key: publish_date
Value: [2000-12-01]
Key: description
Value: [The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.]
Key: book
Value: [ ]
Attributes: [id: bk112]
Key: author
Value: [Galos, Mike]
Key: title
Value: [Visual Studio 7: A Comprehensive Guide]
Key: genre
Value: [Computer]
Key: price
Value: [49.95]
Key: publish_date
Value: [2001-04-16]
Key: description
Value: [Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.]
import Foundation
public struct Node: CustomStringConvertible {
public var children: [Node] = []
public var key = ""
public var leafValue: String? = nil
public var cleanLeafValue: String? {
if var leafValue = leafValue {
leafValue = (leafValue as NSString).replacingOccurrences(of: "\n", with: "")
leafValue = (leafValue as NSString).replacingOccurrences(of: "\\s+", with: " ", options: [.regularExpression], range: NSMakeRange(0, leafValue.characters.count))
if !leafValue.isEmpty {return leafValue}
}
return nil
}
public var attributes: [NSObject: AnyObject]? = nil
public var description: String {return "Key: \(key) Value: \(leafValue) Attributes: \(attributes) Children: \(children)"}
}
public extension Node {
public func showNode(_ indent: Int = 0) {
let indentation = String(repeating: " ", count: indent)
Swift.print(indentation)
Swift.print("Key: \(key) ")
if let leafValue = cleanLeafValue {Swift.print("Value: [\(leafValue)] ")}
if let attributes = attributes {
if !(attributes.keys).isEmpty {
print("Attributes: ", terminator: "")
debugPrint(attributes)
}
}
Swift.print("")
for child in children {child.showNode(indent + 4)}
}
}
public extension Node {
public var keys: [String] {return children.map({$0.key})}
public func childrenWithKey(_ keyString: String) -> [Node]{
return children.filter({$0.key == keyString})
}
public func childWithKey(_ keyString: String) -> Node? {
return childrenWithKey(keyString).first
}
}
public final class MyXMLParser: NSObject, XMLParserDelegate {
var stack: [Node] = []
public static func parse(xmlString: String) -> Node? {
let instance = MyXMLParser()
return instance.parseXMLString(xmlString)
}
public static func parse(xmlData: Data) -> Node? {
let instance = MyXMLParser()
return instance.parseXMLData(xmlData)
}
public func parseXMLData(_ xmlData: Data) -> Node? {
stack.append(Node())
let parser = Foundation.XMLParser(data: xmlData)
parser.shouldResolveExternalEntities = true
parser.delegate = self
parser.parse()
let parent = stack.last
return parent?.children.last
}
public func parseXMLString(_ xml: String) -> Node? {
if let data = xml.data(using: String.Encoding.utf8, allowLossyConversion: false) {
return parseXMLData(data)
}
return nil
}
public func parser(
_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String] = [:])
{
var node = Node()
node.key = elementName
node.attributes = attributeDict as [NSObject : AnyObject]?
stack.append(node)
}
public func parser(
_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?)
{
let node = stack.removeLast()
var parent = stack.removeLast()
parent.children.append(node)
stack.append(parent)
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
if !stack.isEmpty {
var node = stack.removeLast()
if let leafValue = node.leafValue {
node.leafValue = leafValue + string
} else {
node.leafValue = string
}
stack.append(node)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment