gpt4 book ai didi

java - 在 Java 中解析 XML 文件

转载 作者:行者123 更新时间:2023-11-29 06:19:47 24 4
gpt4 key购买 nike

在下面的示例代码中,我对列表有疑问。我的教授将 Document 对象添加到 ArrayList。看起来这只会将一个文档对象添加到列表中,而不是每个单独的节点。但随后查看 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 提要,这似乎是错误的方法。我认为您需要执行深度优先算法以使输出更易于理解。在那种情况下,您可以使用 Stack 而不是 List。)

关于java - 在 Java 中解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3601950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com