ios - 如何在 iOS 中将字符从一个位置修剪到另一个位置( Objective-C )?

标签 ios objective-c xml nsstring

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

相关文章:

iphone - 如果原始 CGPoints 丢失,如何将存储的 CGPath 重绘为贝塞尔路径

objective-c - 如何将 Objective C View Controller 推送到 Swift View Controller

javascript - 从 url 无法将 XML 导入到 html

xml - JAXB - 仅为元素的特定子类型设置 XmlAdapter?

java - Android - 从相对布局中删除 ImageView

iphone - 如何在不使用 ios 应用程序内购买的情况下处理付款?

ios - 是否可以获取 TouchID 信息并与指纹数据库进行比较?

iphone - UIScrollView 一次只向一个方向滚动

ios - 不确定在代码中放置 storageRef.downloadURL 的位置

ios - sizeThatFits有时返回的高度比iOS 8中的文本高(或小于)一行