使用 DOM 解析 XML [英] XML Parsing using DOM
问题描述
我有一个包含以下数据的 XML...
I have an XML with the following data...
<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 解析器来解析它...到目前为止我已经使用了以下代码:
I want to parse this using JDOM parser in a servlet...I have used the following code so far:
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" ));
}
}
但是我的代码会重复 3 次返回 root 的第一个子元素的值.我认为这是因为我将所有 3 个孩子的名字都作为电影".
However my code returns values for the first child element of root repetitively 3 times. I assume this is because i have all 3 child name as "movie" only.
所以我想区分这些,并使用 Title="par" 等属性计算下一部电影的孩子.
So i want to distinguish these, and make the count to next movie child with attributes like Title="par" etc..
一直在想这个,但找不到.帮助将是非常可观的
Been figuring out this since so long but could not find. Help would be really appreciable
推荐答案
你的方法不起作用,因为即使你循环了 3 次,你总是通过以下方式获取相同的(第一个)节点:
Your's is not working because even though you are looping 3 times, you are always fetching the same (first) node through:
Element movieAtt = doc.getRootElement().getChild("movie");
试试这个:(未经测试)
Try this: (untested)
Element root = doc.getRootElement();
List children = root.getChildren();
out.println(root);
if (children != null)
{
for (Element child : children)
{
out.println(child.getAttributeValue( "Title" ));
}
}
这篇关于使用 DOM 解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!