Pripyat
Pripyat

Reputation: 2937

Cocoa - Insert text between tags

I was wondering how it is possible to insert text between HTML tags in Cocoa. I am displaying source code in a NSTextView - example:

<html>
<head>
<title>test</title>
</head>
<body>hello!</body>
</html>

The code above can vary in size, but what should I do if I wanted to insert say <link rel="apple-touch-icon" href="webclip.png" /> at any place between the <head> tags?

Edit: To clarify, I am not looking on how to insert text into an NSTextView, but on how to insert the text between the head tags that are already in the textview. I'm working on a HTML editor.

Thank you! :)

Upvotes: 0

Views: 347

Answers (2)

Alex
Alex

Reputation: 26859

Having not written an HTML editor before, I'm not entirely sure of the best approach for this. However, you'll obviously need some way of parsing the HTML. Since you're using Cocoa, you've got a few options.

  • NSXMLParser This is a SAX-style event -driven parser. You implement NSXMLParserDelegate, which has methods that get called when the parser encounters various XML components (elements, attributes, text, etc.)
  • NSXML This is a tree-based XML parser, and I'm not sure how well it plays with HTML. It does, however, have the advantage of being able to run XPath queries which can be very helpful when you're looking for a specific element.
  • libxml This is a C library which operates at a much lower level than Cocoa. However, it is by far the most capable of the three. It can work in both an event-driven mode and a tree-oriented mode. Plus, it also has HTML-specific capabilities. Unfortunately, it is not that friendly to use. You'll find yourself casting stuff between C strings and NSString objects a lot.
    However, I've used libxml extensively in an iOS app for parsing XML and it works beautifully once you get used to the C-style interface. I'm sure it works just as nicely on Mac OS X, too. This is probably what I'd recommend for your problem.

Upvotes: 1

Peter Hosey
Peter Hosey

Reputation: 96353

A text view owns a text storage, which is a kind of mutable attributed string. You can replace an empty range with the string you want to insert to insert it.

Of course, you will need to parse the HTML to determine where to insert it.

Upvotes: 0

Related Questions