Java 使用DOM解析XML
我有一个包含以下数据的XMLJava 使用DOM解析XML,java,xml,parsing,jdom,Java,Xml,Parsing,Jdom,我有一个包含以下数据的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="Uni
<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" ));
}
}
试试看
{
doc=builder.build(url);
元素根=doc.getRootElement();
List children=root.getChildren();
out.println(根);
对于(int i=0;i
但是,我的代码重复3次返回root的第一个子元素的值。我想这是因为我只有3个孩子的名字作为“电影”
所以我想区分这些,并使用Title=“par”等属性对下一个电影子级进行计数
很久以来一直在想这个问题,但找不到。帮助将非常有用因为即使循环3次,也总是通过以下方式获取相同(第一个)节点:
Element movieAtt = doc.getRootElement().getChild("movie");
试试这个:
(未经测试)
最好的方法是从
children
列表中获取属性,而不是再次请求movieAtt
我从未使用过JDOM,但我的伪代码如下:
for (int i = 0; i < children.size(); i++) {
Element e = children.get(i);
String title = e.getAttributeValue("Title");
}
for(int i=0;i
请注意,您可能需要将您的列表子项
强制转换为元素的列表。它工作于Element movieAtt=(Element)doc.getRootElement().getChildren(“movie”).get(i);您可以编写一个简单的助手类来完成围绕DOM的任务。看到这个了吗
for (int i = 0; i < children.size(); i++) {
Element e = children.get(i);
String title = e.getAttributeValue("Title");
}