如何在iOS中将角色从一个位置修剪到另一个位置(目标C)



我的问题是,我想从字符串中删除一些字符。我的字符串包含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>

我需要从打开标签CCD_ 1修剪到关闭标签</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);

希望这能有所帮助。

尝试以下代码:

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);

希望它能有所帮助:)

相关内容

最新更新