В приведенном ниже примере кода у меня есть вопрос о списке. Мой prof добавляет объект Document в ArrayList. Похоже, это просто добавит в список один объект Document, а не каждый отдельный узел. Но затем, глядя на цикл while, кажется, что он получает элемент в индексе 0, анализирует информацию, затем удаляет этот элемент, чтобы он мог посмотреть следующую информацию. Таким образом, похоже, что в ArrayList больше происходит только один объект Document. Является ли то, что происходит в части ArrayList/while? Я запутался в том, как работает этот код. Заранее спасибо!Разбор XML-файла в Java
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();
}
}
}