📄 xml.java
字号:
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
public class xml
{
static Document document;
public static void main(String [] args)
{
/*
if(args.length!=1)
{
System.out.println("加载XML文档");
return;
}
*/
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db=dbf.newDocumentBuilder();
document=db.parse("X:\\java\\xml\\src\\studentInfo.xml");
Node root=document.getDocumentElement();
NodeList childs=root.getChildNodes();
//printNode(root);
getElement(childs);
}
catch(SAXException se)
{
Exception e=se;
if(se.getException()!=null)
e=se.getException();
e.printStackTrace();
}
catch(ParserConfigurationException pe)
{
pe.printStackTrace();
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
public static void getElement(NodeList childs)
{
int i=0;
if(childs.getLength()==0)
{
System.out.println("该节点没有子结点");
}
for(i=0;i<childs.getLength();i++)
{
Node node=childs.item(i);
short nodetype=node.getNodeType();
if(nodetype==Node.ELEMENT_NODE)
{
String name=node.getNodeName();
String attrValue="",attrName="";
System.out.println("This is element! name is:"+name);
if(node.hasAttributes())
{
Node attrNode=node.getAttributes().item(0);
attrName=attrNode.getNodeName();
attrValue=attrNode.getNodeValue();
System.out.println("This element arrt is:"+attrValue+";attrnameis:"+attrName);
}
if(node.hasChildNodes())
{
getElement(node.getChildNodes());
}
}
if(nodetype==Node.TEXT_NODE)
{
String txtName=node.getNodeName();
Node thisparent=node.getParentNode();
Node txtNode=thisparent.getChildNodes().item(0);
String txtValue=txtNode.getNodeValue();
if(txtValue.trim().length()>0)
{
System.out.println("txtName="+txtName+";txtValue="+txtValue.trim());
}
}
}
}
private static void printNode(Node anode)
{
switch (anode.getNodeType())
{
case Node.ELEMENT_NODE:
System.out.println(anode.getNodeName() + ", " + anode.getNodeValue());
if (anode.hasAttributes())
{
NamedNodeMap attrs = anode.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node node = attrs.item(i);
System.out.println("\t" + node.getNodeName()
+ ", " + node.getNodeValue());
}
}
break;
case Node.TEXT_NODE:
String txtValue = anode.getNodeValue().trim();
if (txtValue.length() > 0)
System.out.println(anode.getNodeName()
+ ", " + txtValue);
break;
default:
System.out.println(
anode.getNodeName() + ", "
+ anode.getNodeValue());
break;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -