rdomxml.java

来自「java中关于XML的解析」· Java 代码 · 共 36 行

JAVA
36
字号
package temp;

import javax.xml.parsers.*;
import org.w3c.dom.*;

/**该程序是在java中实现读xml文件的程序,读入的文件名为"result/rDomXml.xml"
   其中的classpath需要加入crimson.jar路径。**/

public class rDomXml
{
	public static void main(String args[])throws Exception
	{
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		DocumentBuilder bulider=factory.newDocumentBuilder();
		Document doc=bulider.parse("result/rDomXml.xml");	//读rDomXml.xml文件
		
		NodeList nl=doc.getElementsByTagName("Book");	//计算Book属性的个数
		for(int i=0;i<nl.getLength();i++){
			Element node=(Element)nl.item(i);
			//读入各项属性
			System.out.println("BookName is :" + 
								node.getElementsByTagName("bookName").item(0).getFirstChild().getNodeValue().trim());

			System.out.println("BookAuthor is :" + 
								node.getElementsByTagName("bookAuthor").item(0).getFirstChild().getNodeValue().trim());

			System.out.println("BookISBN is :" + 
								node.getElementsByTagName("bookISBN").item(0).getFirstChild().getNodeValue().trim());

			System.out.println("BookPrice is :" + 
								node.getElementsByTagName("bookPrice").item(0).getLastChild().getNodeValue().trim()+"\n\n");
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?