iosobjective-cmacosnsxmlnsxmlelement

Get text value only from NSXMLElement without the text of child nodes


I use KissXML, it is a drop replacement for NSXMLDocument, etc. This is contents of my NSXMLElement:

<ar>
    <k>baker</k>
    <tr>ˈbeɪkə</tr>
    baker пекарь, булочник
</ar>

I want to get the text value of a NSXMLElement Node without the text of all child nodes. So, it should return only:

baker пекарь, булочник

This is not working:

_articleText = [xmlElement stringValue];

It returns everything, including text of tr and k child nodes.

P.S. I got this ar node using XPath and I'm searching for XPath solution preferably, I do not want to remove substrings.

NSArray *array = [self.xmlDocument nodesForXPath:@"/xdxf/ar" error:&error];

Solution

  • Assuming 'array' contains only one element, then 's' will contain the string of interest:

    NSArray *array = [self.xmlDocument nodesForXPath:@"/xdxf/ar" error:&error];
    if([array count] > 0) { 
        NSArray *childrenOfAr = [array[0] children];    
        for(NSXMLNode *n in childrenOfAr) {
            if([n kind] == NSXMLTextKind) {
                 NSString *s = [n stringValue];
            }
        }
    }
    

    A faster way is to look for text() in the Xpath query:

    NSArray *array = [self.xmlDocument nodesForXPath:@"/xdxf/ar/text()" error:&error];
    if([array count] > 0) { 
        NSString *s = [array[0] stringValue]; 
    }