我想要HTML字符串中的Only Body Part。
下面的代码是完整的HTLM字符串:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 45.0px; font: 37.9px 'Times New Roman'; color: #000000; -webkit-text-stroke: #000000}
span.s1 {font-family: 'Times New Roman'; font-weight: normal; font-style: normal; font-size: 37.92pt; font-kerning: none}
span.s2 {font-family: 'TimesNewRomanPS-BoldMT'; font-weight: bold; font-style: normal; font-size: 37.92pt; font-kerning: none}
</style>
</head>
<body>
<p class="p1"><span class="s1">-1 Water damage and dry-rot observed on fascia boards around </span><span class="s2">the perimeter of the structur</span><span class="s1">e.</span></p>
</body>
</html>
我只希望下面的部分没有CSS。
<body>
<p class="p1"><span class="s1">-1 Water damage and dry-rot observed on fascia boards around </span><span class="s2">the perimeter of the structur</span><span class="s1">e.</span></p>
</body>
答案 0 :(得分:0)
NSString * string;
NSString * pattern;
string = html// [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"File" withExtension:nil] encoding:NSASCIIStringEncoding error:nil];
pattern = @"<body>[ \\w\\d\\n<>=\\\"-/]*</body>";
NSRegularExpression * regex = [[NSRegularExpression alloc]initWithPattern:pattern options:(NSRegularExpressionAnchorsMatchLines) error:nil] ;
NSTextCheckingResult * result = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
if (result != nil){
NSString * resultString = [string substringWithRange: result.range];
NSLog(resultString);
}
答案 1 :(得分:0)
在Mac上,如果您仍然想要样式,但又希望将样式嵌入标签中,则可以要求NSAttributedString排除这样的样式标签:
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSExcludedElementsDocumentAttribute: @[@"style"]
};
NSData *htmlData = [attributedString dataFromRange:NSMakeRange(0, attributedString.length) documentAttributes:documentAttributes error:NULL];
通过这种方式,您将在标签中嵌入所有样式。
很遗憾,它在iOS上不可用。
答案 2 :(得分:0)
我使用webView而不是textView来显示属性字符串。
NSString *strState = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
此方法将返回不带CSS的HTML字符串。