这可能是一个基本问题,但我有一个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
作为发言人和他/她的行并将其添加到字典中。之后,我想将字典添加到数组中,然后清除字典。
我该怎么做?
由于
答案 0 :(得分:2)
我从你问题中的一个原始标记xcode推断出你在Objective-C中正在做的事情。我进一步假设你想使用NSXMLParser
。
所以,我们假设你有(a)一个speeches
的可变数组; (b)当前speech
的可变字典; (c)每个发言的可变数组lines
; (d)一个可变字符串value
,它将捕获在元素名称的开头和该元素名称的结尾之间找到的字符。
然后,您必须实现NSXMLParserDelegate
方法。例如,正如您正在解析的那样,在didStartElement
中,如果遇到语音元素名称,则会创建一个字典:
if ([elementName isEqualToString:@"SPEECH"]) {
speech = [[NSMutableDictionary alloc] init];
lines = [[NSMutableArray alloc] init];
}
else
{
value = [[NSMutableString alloc] init];
}
当您遇到foundCharacters
中的字符时,您会将这些字符附加到value
:
[value appendString:string];
并且,在didEndElement
中,如果您遇到扬声器,请设置它,如果您遇到一条线路,请添加它,如果您遇到SPEECH
结束标记,请继续添加语音(将SPEAKER
和LINES
添加到您的演讲数组中:
if ([elementName isEqualToString:@"SPEAKER"]) {
[speech setObject:value forKey:@"SPEAKER"];
}
else if ([elementName isEqualToString:@"LINE"]) {
[lines addObject:value];
}
else if ([elementName isEqualToString:@"SPEECH"]) {
[speech setObject:lines forKey:@"LINES"];
[speeches addObject:speech];
speech = nil;
lines = nil;
}
value = nil;
有关详细信息,请参阅Event-Driven XML Programming Guide或google&#34; NSXMLParser教程&#34;。
答案 1 :(得分:0)
如果您使用c#,并且每个SPEECH
只有1 SPEAKER
,您可以执行以下操作
XDocument xdoc = XDocument.Load("XMLFile1.xml");
List<string> lines = xdoc.Descendants("SPEECH").Where(e => e.Element("SPEAKER").Value.ToUpper() == "NARRATOR").Elements("LINE").Select(e => e.Value).ToList();