解析器 - 如何读取文件?
问题描述:
我是一个java初学者,也是编程初学者,我想实现一个DOM解析器。我的问题:我不知道如何将文件读入解析器。我试图在DOM上使用IBM-Parser。解析器 - 如何读取文件?
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文件的一种简单方法。
你已经发布了很多代码,但是你没有指定代码实际导致什么问题。 Doe坐有错误吗? - >发布它们 – LionC
也发布你的XML文件。 – Amador