Modifying an HTML/XML document

  1. Changing text contents
  2. Moving nodes
  3. Modifying Nodes and Attributes
  4. Creating new nodes (Unimplemented for now)
  5. Wrapping a NodeSet (Unimplemented for now)

Changing text contents

Assuming we have the following HTML document:

[sample.html]
<body>
  <h1>Three's Company</h1>
  <div>A love triangle.</div>
</body>

Let’s change the header’s text contents:

let html = try! String(contentsOfFile: "sample.html", encoding: NSUTF8StringEncoding)
guard let doc = HTML(html: html, encoding: NSUTF8StringEncoding) else {
    return
}
var h1 = doc.at_css("h1")!
h1.content = "Snap, Crackle & Pop"

print(doc.body?.toHTML)

// "<body>
// <h1>Snap, Crackle &amp; Pop</h1>
// <div>A love triangle.</div>
// </body>"

You’ll notice that, when you use #content=, entities are properly escaped.

Moving nodes

The simplest method of moving a node is assign its parent:

var h1  = doc.at_css("h1")!
var div = doc.at_css("div")!
h1.parent = div

print(doc.body?.toHTML)

// "<body>
// <div>A love triangle.<h1>Three's Company</h1></div>
// </body>"

But you could also arrange it next to other nodes:

div.addNextSibling(h1)

print(doc.body?.toHTML)

// "<body>
// <div>A love triangle.</div>
// <h1>Three's Company</h1>
// </body>"

Modifying Nodes and Attributes

h1.tagName = "h2"
h1["class"] = "show-title"

print(doc.body?.toHTML)

// "<body>
// <h2 class=\"show-title\">Three's Company</h2>
// <div>A love triangle.</div>
// </body>"

Creating new nodes

(Unimplemented for now)

Wrapping a NodeSet

(Unimplemented for now)