From d6f5434ab89bcdbc3f0ab611a43a174df12cdb17 Mon Sep 17 00:00:00 2001 From: iska Date: Wed, 8 Apr 2015 00:29:00 +0200 Subject: [PATCH] Add implementation for text-content in the HTML Element --- HTMLKit/HTMLDocument.m | 4 ++++ HTMLKit/HTMLElement.m | 19 ++++++++++++++++--- HTMLKit/HTMLNode.h | 2 ++ HTMLKit/HTMLNode.m | 10 ++++++++++ HTMLKit/HTMLText.m | 2 +- 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/HTMLKit/HTMLDocument.m b/HTMLKit/HTMLDocument.m index 8ee402d..2bd8ed6 100644 --- a/HTMLKit/HTMLDocument.m +++ b/HTMLKit/HTMLDocument.m @@ -46,6 +46,10 @@ - (HTMLNode *)adoptNode:(HTMLNode *)node { + if (node == nil) { + return nil; + } + if (node.type == HTMLNodeDocument) { [NSException raise:HTMLKitNotSupportedError format:@"%@: Not Fount Error, adopting a document node. The operation is not supported.", NSStringFromSelector(_cmd)]; diff --git a/HTMLKit/HTMLElement.m b/HTMLKit/HTMLElement.m index a363003..fb0d739 100644 --- a/HTMLKit/HTMLElement.m +++ b/HTMLKit/HTMLElement.m @@ -7,9 +7,11 @@ // #import "HTMLElement.h" +#import "HTMLDocument.h" +#import "HTMLText.h" + #import "HTMLOrderedDictionary.h" #import "NSString+HTMLKit.h" -#import "HTMLText.h" @interface HTMLElement () { @@ -84,8 +86,19 @@ - (NSString *)textContent { -#warning Implement Traversing - return nil; + NSMutableString *content = [NSMutableString string]; + for (HTMLNode *node in self.treeEnumerator) { + if (node.type == HTMLNodeText) { + [content appendString:[(HTMLText *)node data]]; + } + } + return content; +} + +- (void)setTextContent:(NSString *)textContent +{ + HTMLText *node = [[HTMLText alloc] initWithData:textContent]; + [self replaceAllChildNodesWithNode:node]; } #pragma mark - NSCopying diff --git a/HTMLKit/HTMLNode.h b/HTMLKit/HTMLNode.h index 394ce18..00d1f08 100644 --- a/HTMLKit/HTMLNode.h +++ b/HTMLKit/HTMLNode.h @@ -73,6 +73,8 @@ typedef NS_ENUM(short, HTMLNodeType) - (HTMLNode *)replaceChildNode:(HTMLNode *)node withNode:(HTMLNode *)replacement; +- (void)replaceAllChildNodesWithNode:(HTMLNode *)node; + - (HTMLNode *)removeChildNode:(HTMLNode *)node; - (HTMLNode *)removeChildNodeAtIndex:(NSUInteger)index; diff --git a/HTMLKit/HTMLNode.m b/HTMLKit/HTMLNode.m index b52b935..475aa21 100644 --- a/HTMLKit/HTMLNode.m +++ b/HTMLKit/HTMLNode.m @@ -165,6 +165,16 @@ return child; } +- (void)replaceAllChildNodesWithNode:(HTMLNode *)node +{ + [self removeAllChildNodes]; + + if (node != nil) { + [self.ownerDocument adoptNode:node]; + [self insertNode:node beforeChildNode:nil]; + } +} + - (HTMLNode *)removeChildNode:(HTMLNode *)child { if (child.parentNode != self) { diff --git a/HTMLKit/HTMLText.m b/HTMLKit/HTMLText.m index 36bb035..8de2a5f 100644 --- a/HTMLKit/HTMLText.m +++ b/HTMLKit/HTMLText.m @@ -21,7 +21,7 @@ { self = [super initWithName:@"#text" type:HTMLNodeText]; if (self) { - _data = [[NSMutableString alloc] initWithString:data]; + _data = [[NSMutableString alloc] initWithString:data ?: @""]; } return self; }