DMO解析.2

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


public class DOMprinter {

public static void print(Node node)
{
System.out.println(node.getNodeName()+"  "+node.getNodeValue());
}
public static void printNode(Node node)
{
Short showtype= node.getNodeType();
if(showtype.equals(Node.PROCESSING_INSTRUCTION_NODE))
{
System.out.println("------IPstart----");
print(node);
System.out.println("------IPend------");
}
else if(showtype.equals(Node.ELEMENT_NODE))
{
System.out.println("------Elementstart----");
print(node);
System.out.println("------Elementend------");
NamedNodeMap attrs=node.getAttributes();
int length=attrs.getLength();
for(int  i=0;i<length;i++)
{
Node  attr=attrs.item(i);
System.out.println("------Attributesstart----");
print(attr);
System.out.println("------Attributesend------");
}
}
else if(showtype.equals(Node.TEXT_NODE))
{
System.out.println("------Textstart----");
print(node);
System.out.println("------Textend------");
}
Node child=node.getFirstChild();
while(child!=null)
{
printNode(child);
child=child.getNextSibling();
}

}
public static void main(String[] args) {
DocumentBuilderFactory dbg=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbg.newDocumentBuilder();
Document doc=db.parse(new File("student.xml"));
// DOMprinter domprinter=new DOMprinter();
// domprinter.printNode(doc);
printNode(doc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}
///////
对应的 XML
<?xml version="1.0" encoding="Gb2312"?>
<students>
<student ar="01">
<name>张三</name>
<age>18</age>
</student>
<student ar="02">
<name>李四</name>
<age>19</age>
</student>
</students>

你可能感兴趣的:(java,xml)