[英]Parsing an XML file in Java
在下面的示例代码中,我对列表有疑问。 我的教授将Document对象添加到ArrayList中。 看来这只是将一个Document对象添加到列表中,而不是将每个Node添加到列表中。 但是,然后查看while循环,似乎他在索引0处获取了该项目,解析了该信息,然后删除了该项目,以便他可以查看下一个信息。 因此,似乎在ArrayList中发生的事情比仅一个Document对象更多。 ArrayList / while循环部分中发生了什么吗? 我对这段代码的工作方式感到困惑。 提前致谢!
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class RSSReader {
public static void main(String[] args) {
File f = new File("testrss.xml");
if (f.isFile()) {
System.out.println("is File");
RSSReader xml = new RSSReader(f);
}
}
public RSSReader(File xmlFile) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(doc);
while(nodeList.size() > 0)
{
Node node = nodeList.get(0);
if (node instanceof Element) {
System.out.println("Element Node: " + ((Element)node).getTagName());
NamedNodeMap attrMap = node.getAttributes();
for(int i = 0; i < attrMap.getLength(); i++)
{
Attr attribute = (Attr) attrMap.item(i);
System.out.print("\tAttribute Key: " + attribute.getName()
+ " Value: " + attribute.getValue());
}
if(node.hasAttributes())
System.out.println();
}
else if(node instanceof Text)
System.out.println("Text Node: " + node.getNodeValue());
else
System.out.println("Other Type: " + node.getNodeValue());
if(node.hasChildNodes())
{
NodeList nl = node.getChildNodes();
for(int i = 0; i < nl.getLength(); i++)
{
nodeList.add(nl.item(i));
}
}
nodeList.remove(0);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}
我认为您的教授在此演示的方法称为广度优先算法。 循环中的关键代码块是
if(node.hasChildNodes())
{
NodeList nl = node.getChildNodes();
for(int i = 0; i < nl.getLength(); i++)
{
nodeList.add(nl.item(i));
}
}
在处理列表中的元素之后,如果该元素具有要处理的子元素,则此代码将被破解。 如果是这样,它们将被添加到要处理的列表中。
我使用此算法时,首先处理根元素,然后再处理其子项,然后再处理其子项,再处理其下的子项,依此类推,直到树上只有叶子为止。
(附带说明:对于XML文档,尤其是RSS feed,这似乎是错误的方法。我想您想使用“深度优先”算法来使输出更易于理解。在这种情况下,您可以使用堆栈而不是列表。)
每个节点的每个子节点都通过以下代码添加到List<Node>
:
if(node.hasChildNodes())
{
NodeList nl = node.getChildNodes();
for(int i = 0; i < nl.getLength(); i++)
{
nodeList.add(nl.item(i));
}
}
基本上,这意味着将访问文档中的每个节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.