【问题标题】:How to trim characters from a position to another position in iOS (Objective C)?如何在iOS(目标C)中将字符从一个位置修剪到另一个位置?
【发布时间】:2016-05-02 10:45:35
【问题描述】:

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

我需要从开始标签&lt;MainCategories&gt; 修剪到结束标签&lt;/MainCategories&gt;。 怎么做??所以这里我的起始字符是&lt;MainCategories,结束字符是/MainCategories&gt;

【问题讨论】:

  • NSXMLParser 怎么样?
  • 我在 xml 解析器中解析响应。它运作良好。但问题是MainCategory 标签之间的CatIDs 是不需要的。但需要SubCategories 内的CatIDs。当我使用NSXMLParser 时,所有CatIDs 都会被解析。这让我一团糟
  • 您只需保留一个标志,表明您是否在MainCategories 标签内。您可以从对委托 didStartElementdidEndElement 方法的调用中了解这一点
  • 是的,我改变了一点,就像你说的那样

标签: ios objective-c xml nsstring


【解决方案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);

希望这会有所帮助。

【讨论】:

  • 哦,我的朋友,它很快。我在做目标 c。我不知道斯威夫特。
  • 哦,我的上帝...哦,它工作了..它工作了。谢啦。如果可能的话 5 票,我会给你 5。我被搞砸了
【解决方案2】:

试试下面的代码:

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

希望它会有所帮助:)

【讨论】:

  • 它有帮助。但实际上我希望删除标签(MainCategories 和 /MainCategories)之间的那些字符(CatID 标签),包括该标签。
猜你喜欢
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
相关资源
最近更新 更多