我的问题是,我想从我的字符串中删除一些字符。我的字符串包含 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>
最佳答案
试试这个
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);
希望这对您有所帮助。
关于ios - 如何在 iOS 中将字符从一个位置修剪到另一个位置( Objective-C )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980574/