我是一名java-beginner,也是编程初学者,我想实现一个DOM-Parser。我的问题:我不知道如何将文件读入解析器。我尝试将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;
}
}
}
}
谢谢!
答案 0 :(得分:1)
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文件的简单方法。