使用JDOM获取XML中的多行

时间:2015-09-29 16:33:03

标签: xml jdom

我有一个代码片段,可以打印出XML文档的一部分:

<SPEECH>
<SPEAKER>KENT</SPEAKER>
<LINE>I thought the king had more affected the Duke of</LINE>
<LINE>Albany than Cornwall.</LINE>
</SPEECH>

代码段:

List<Element> speech = scene.getChildren("SPEECH");
for(int a = 0; a < speech.size(); a++)
    {
        Element speak = speech.get(a);
        System.out.println(speak.getChildren());
        System.out.println("SPEAKER : " + speak.getChildText("SPEAKER"));
        System.out.println("LINE : " + speak.getChildText("LINE")); 
    }

问题是它只打印出XML中的第一行。有人可以建议在XML文件中计算和打印多个LINES的方法(注意,XML的某些部分有两行以上)?

以下是我目前在我的代码中导入的库:

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

1 个答案:

答案 0 :(得分:1)

您确实需要使用enhanced-for循环。考虑一下:

for(Element speech : scene.getChildren("SPEECH")) {
    for (Element part : speech.getChildren()) {
        System.out.println(part.getName() + " : " + part.getText());
    }
}
相关问题