XML仅解析某些子元素

问题描述 投票:0回答:2

这可能是一个基本问题,但是,我有一个xml格式的剧本。我想抓住演讲者和演讲者在字典中的所有行,以便将其添加到数组中。这是格式

 <SPEECH>
    <SPEAKER>Narrator</SPEAKER>
    <LINE>Two households, both alike in dignity,</LINE>
    <LINE>In fair Verona, where we lay our scene,</LINE>
    <LINE>From ancient grudge break to new mutiny,</LINE>
    <LINE>Where civil blood makes civil hands unclean.</LINE>
    <LINE>From forth the fatal loins of these two foes</LINE>
    <LINE>A pair of star-cross'd lovers take their life;</LINE>
    <LINE>Whole misadventured piteous overthrows</LINE>
    <LINE>Do with their death bury their parents' strife.</LINE>
    <LINE>The fearful passage of their death-mark'd love,</LINE>
    <LINE>And the continuance of their parents' rage,</LINE>
    <LINE>Which, but their children's end, nought could remove,</LINE>
    <LINE>Is now the two hours' traffic of our stage;</LINE>
    <LINE>The which if you with patient ears attend,</LINE>
    <LINE>What here shall miss, our toil shall strive to mend.</LINE>
</SPEECH>

所以我想抓住Narrator作为发言人和他/她拥有的台词,并将其添加到词典中。之后,我想将字典添加到数组中,然后清除字典。

我该怎么做?

谢谢

iphone xml xml-parsing nsxmlparser
2个回答
2
投票

我从问题中的原始标签之一推断出,您正在Objective-C中进行此操作。我将进一步假设您要使用NSXMLParser

因此,假设您有(a)个NSXMLParser的可变数组; (b)当前speeches的可变字典; (c)每个语音的speech可变数组; (d)可变字符串lines,它将捕获在元素名称的开头和元素名称的结尾之间找到的字符。

然后,您必须实现value方法。例如,在解析时,在NSXMLParserDelegate中,如果遇到语音元素名称,则创建字典:

NSXMLParserDelegate

[在didStartElement中遇到字符时,请将它们附加到didStartElement

if ([elementName isEqualToString:@"SPEECH"]) {
    speech = [[NSMutableDictionary alloc] init];
    lines  = [[NSMutableArray alloc] init];
}
else 
{
    value = [[NSMutableString alloc] init];
}

并且,在foundCharacters中,如果遇到扬声器,请进行设置,如果遇到线路,则添加它,如果遇到foundCharacters结束标记,请继续添加语音(带有value[value appendString:string]; 到您的语音阵列:

didEndElement

有关更多信息,请参见didEndElement或Google“ NSXMLParser教程”。


0
投票

如果使用c#并且每个SPEECH只有1个SPEAKER,则可以执行以下操作

LINES
© www.soinside.com 2019 - 2024. All rights reserved.