我编写了这段代码来解析 XML 文件。我想以树(根、子、孙子)的形式打印 o/p。但是它将每个节点(子节点和孙节点)打印为根节点的子节点。
import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
public class Parsing{
public static void traverse (Node n) throws Exception
{
// Extract node info:
String TextNode = "TextNode";
String AttrVal = "";
int ind;
String nodename = n.getNodeName();
String valueStr = n.getNodeValue();
Boolean bo = n.hasAttributes();
String xml1 = "";
if (valueStr != null)
valueStr = valueStr.trim();
// Print and continue traversing.
if(!nodename.equals("#text"))
{
if(bo==true)
{
NamedNodeMap nm1 = n.getAttributes();
if(valueStr==null)//If node has no value
System.out.println(""+ n.getNodeName());
else
System.out.println( "" + n.getNodeName() + " Value = " + valueStr + " " );
System.out.println( "\t\tAttributes: ");
for(int i = 0 ; i<nm1.getLength() ; i++)
{
Attr attribute = (Attr)nm1.item(i);
AttrVal = attribute.getValue();
ind = AttrVal.indexOf(":");
ind++;
System.out.println( "\t\t\t" + attribute.getName()+" = "+attribute.getValue());
}
{
if(valueStr==null)
System.out.println (" " + n.getNodeName() );
else
System.out.println (" " + n.getNodeName() + " Value = " + valueStr + " ");
}
}
else
{
if(!valueStr.equals(""))
System.out.println (" " + TextNode + " Value = " + valueStr + " ");
}
// Now traverse the rest of the tree in depth-first order.
if (n.hasChildNodes())
{
// Get the children in a list.
NodeList nl = n.getChildNodes();
// No. of children
int size = nl.getLength();
for (int i=0; i<size; i++)
// Recursively traverse each of the children.
traverse (nl.item(i));
}
}
public static void parse (String a1){
try
{
System.out.println("Name" + a1);
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File(a1));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
Element root = doc.getDocumentElement();
System.out.println("ROOT ELEMENT IS" + root);
traverse (root);
}
catch (Throwable t)
{
t.printStackTrace ();
}
}
}