0

这可能是一个基本问题,但我有一个 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演讲者和他/她拥有的台词并将其添加到字典中。之后,我想将字典添加到数组中,然后清除字典。

我怎样才能做到这一点?

谢谢

4

2 回答 2

2

我从您问题中的一个原始标签中推断出您在 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结束标签,继续添加演讲(与它的SPEAKERLINES你的演讲阵列:

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;

有关更多信息,请参阅事件驱动 XML 编程指南或谷歌“NSXMLParser 教程”。

于 2013-06-21T05:43:44.653 回答
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();
于 2013-06-20T22:56:26.927 回答