views:

42

answers:

2

Hello,

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! :)

A: 

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.

Peter Hosey
I am aware of that - i am asking how I determine where I need to insert it?
David Schiefer
You asked how to insert text. That's the question I answered. How to parse HTML is a different question.
Peter Hosey
A: 

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.
Alex
All three of these rely on the input being valid XML (i.e., XHTML). SGML-based HTML, including HTML 5 and unvalidated “tag soup” (not that these are mutually exclusive), will almost certainly cause an XML parser to choke and return an error rather than give you a complete parse of the document.
Peter Hosey
I do use NSXMLParser, but only for reading META Tags and get the path for the CSS Sheet. All I need to know is how I can insert text between two tags? so kindof like NSTextView's `insertText:` method, but between tags.
David Schiefer