正则表达式在标签内获得价值 [英] Regex to get value within tag
问题描述
我有一组返回的XML示例:
<rsp stat="ok">
<site>
<id>1234</id>
<name>testAddress</name>
<hostname>anotherName</hostname>
...
</site>
<site>
<id>56789</id>
<name>ba</name>
<hostname>alphatest</hostname>
...
</site>
</rsp>
我想提取<name></name>
中的所有内容,而不提取标签本身,并仅将其用于第一个实例(或基于其他测试选择哪个项目).
使用正则表达式可以吗?
此类任务的最佳工具是 如果要使用ID为56789的站点名称,请使用以下XPath: I have a sample set of XML returned back: I want to extract everything within Is this possible with regex? The best tool for this kind of task is XPath. If you want the name of the site which has id 56789, use this XPath: 这篇关于正则表达式在标签内获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!/rsp/site[id='56789']/name
.建议您阅读 W3Schools XPath教程,以快速了解XPath语法.><rsp stat="ok">
<site>
<id>1234</id>
<name>testAddress</name>
<hostname>anotherName</hostname>
...
</site>
<site>
<id>56789</id>
<name>ba</name>
<hostname>alphatest</hostname>
...
</site>
</rsp>
<name></name>
but not the tags themselves, and to have that only for the first instance (or based on some other test select which item). NSURL *rspURL = [NSURL fileURLWithPath:[@"~/rsp.xml" stringByExpandingTildeInPath]];
NSXMLDocument *document = [[[NSXMLDocument alloc] initWithContentsOfURL:rspURL options:NSXMLNodeOptionsNone error:NULL] autorelease];
NSArray *nodes = [document nodesForXPath:@"/rsp/site[1]/name" error:NULL];
NSString *name = [nodes count] > 0 ? [[nodes objectAtIndex:0] stringValue] : nil;
/rsp/site[id='56789']/name
instead. I suggest you read W3Schools XPath tutorial for a quick overview of the XPath syntax.