[英]XML Parsing using DOM
我有一個包含以下數據的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次。 我認為這是因為我所有3個孩子的名字都只有“電影”。
因此,我想區分這些,並使用諸如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" ));
}
}
最好的方法是從children
列表中獲取屬性,而不是再次請求movieAtt
。
我從未使用過JDOM,但是我的偽代碼如下:
for (int i = 0; i < children.size(); i++) {
Element e = children.get(i);
String title = e.getAttributeValue("Title");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.