这可能是一个基本的问题,但是,我有一个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作为演讲者和他/她拥有的行,并将其添加到字典中。之后,我想将字典添加到数组中,然后清除字典。
我该怎么做呢?
谢谢
发布于 2013-06-21 13:43:45
我从你问题中的一个原始标签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;有关更多信息,请参阅或谷歌的"NSXMLParser教程“。
发布于 2013-06-21 06:56:27
如果使用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();https://stackoverflow.com/questions/17224769
复制相似问题