我的问题是,我想从我的字符串中删除一些字符。我的字符串包含xml。所以我需要修剪xml开始标记中的字符到其结束标记。我该怎么办?
例如:我的字符串包含以下xml代码。
<CategoriesResponse xmlns="https://abc.defg.com/hijk">
<MainCategories>
<CatID xsi:type="xsd:int">178</CatID>
<CatID xsi:type="xsd:int">150</CatID>
<CatID xsi:type="xsd:int">77</CatID>
<CatID xsi:type="xsd:int">33</CatID>
<CatID xsi:type="xsd:int">179</CatID>
</MainCategories>
<SubCategories>
//some needed elements should not be trimmed.
</SubCategories>
我需要从开头标记<MainCategories>
修剪到结束标记</MainCategories>
。
怎么做??所以这里我的起始角色为<MainCategories
,结尾角色为/MainCategories>
答案 0 :(得分:1)
试试这个
NSString *str = @"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";
NSRange startRange = [str rangeOfString:@"<MainCategories>"];
NSRange endRange = [str rangeOfString:@"</MainCategories>"];
NSString *replacedString = [str stringByReplacingCharactersInRange:NSMakeRange(startRange.location, (endRange.location+endRange.length)-startRange.location) withString:@""];
NSLog(@"%@",replacedString);
希望这有帮助。
答案 1 :(得分:1)
尝试以下代码:
NSString *strXml=@"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";
strXml=[strXml stringByReplacingOccurrencesOfString:@"<MainCategories>" withString:@"<MainCategories"];
strXml=[strXml stringByReplacingOccurrencesOfString:@"</MainCategories>" withString:@"/MainCategories>"];
NSLog(@"%@",strXml);
希望它会有所帮助:)