gpt4 book ai didi

java - 解析器-如何读取文件?

转载 作者:行者123 更新时间:2023-12-01 13:48:56 26 4
gpt4 key购买 nike

我是一个java初学者,也是一个编程初学者,我想实现一个DOM解析器。我的问题:我不知道如何将文件读入解析器。我尝试将 IBM-Parser 与 DOM 一起使用。

package domparser;
import org.w3c.dom.*;
import com.ibm.xml.parsers.*;

public class domparser
{
public static void main(String[] args)
{
domparser MyParser = new domparser();
MyParser.parse(args[0]);
}

private void parse(String file)
{
NonValidatingDOMParser parser = new NonValidatingDOMParser();
try
{
parser.parse(file);
writeDoc(parser.getDocument().getDocumentElement());
}
catch (Exception e)
{
System.err.println("Fehler: " + e);
}
}

private void writeDoc(Node node)
{
short type = node.getNodeType();
switch (type)
{
case Node.ELEMENT_NODE:
{
String name = "<" + node.getNodeName();
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
int length = attrs.getLength();
for (int i = 0; i < length; i++)
{
Node attr = attrs.item(i);
name += " " + attr.getNodeName();
name += "=\"" + attr.getNodeValue() + "\"";
}
}
name += ">";
System.out.println(name);

NodeList children = node.getChildNodes();
if (children != null)
{
int length = children.getLength();
for (int i = 0; i < length; i++)
writeDoc(children.item(i));
}
break;
}
case Node.TEXT_NODE:
{
System.out.println(node.getNodeValue());
break;
}
}
}
}

谢谢!

最佳答案

File xmlFile = new File("xmlFiles/type.xml");  
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlFile);

doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("type");

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

然后你应该循环并打印取决于你的xml文件,这只是一个不完全适合你的例子......DoucmentBuilderFactory是一种在java中读取XML文件的简单方法。

关于java - 解析器-如何读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20124471/

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