我有一个包含以下数据的 XML...
<movies total="3">
<movie cover="9_pro.jpg" Title="A Very " MovieDuration="1.29" showtime="2:50 PM" theatre="UV3"/>
<movie cover="5_pro.jpg" Title="Par" MovieDuration="1.24" showtime=" 12:00 PM" theatre="University Village 3"/>
<movie cover="8_pro.jpg" Title="PinBts" MovieDuration="1.30" showtime="9:20 PM" theatre="University Village 3"/>
</movies>
我想在 servlet 中使用 JDOM 解析器来解析它...到目前为止我已经使用了以下代码:
try
{
doc=builder.build(url);
Element root = doc.getRootElement();
List children = root.getChildren();
out.println(root);
for (int i = 0; i < children.size(); i++)
{
Element movieAtt = doc.getRootElement().getChild("movie");
//out.println(movieAtt.getAttributeValue( "cover" ));
out.println(movieAtt.getAttributeValue( "Title" ));
//out.println(movieAtt.getAttributeValue( "MovieDuration" ));
//out.println(movieAtt.getAttributeValue( "showtime" ));
//out.println(movieAtt.getAttributeValue( "theatre" ));
}
}
但是我的代码重复返回 root 的第一个子元素的值 3 次。我认为这是因为我的三个 child 的名字都只是“电影”。
所以我想区分这些,并使用 Title="par"等属性对下一个电影子项进行计数。
很久以来一直在想这个问题,但找不到。帮助将非常感激
最佳答案
你的不起作用,因为即使你循环3次,你总是通过以下方式获取相同的(第一个)节点:
Element movieAtt = doc.getRootElement().getChild("movie");
试试这个: (未经测试)
Element root = doc.getRootElement();
List children = root.getChildren();
out.println(root);
if (children != null)
{
for (Element child : children)
{
out.println(child.getAttributeValue( "Title" ));
}
}
关于java - 使用 DOM 进行 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036276/