org.w3c.dom解析xml

本文介绍了一种使用Java解析XML文件的方法,重点展示了如何遍历XML文档的节点,并获取旧类别ID与新类别ID的对应关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml 文件格式如下:

<?xml version="1.0" encoding="UTF-8"?>  
<category>
	<categoryId>  
	    <oldCategoryId>950347</oldCategoryId>  
	    <newCategoryId>959440,959461,959432,959447</newCategoryId>  
	</categoryId> 
	
	<categoryId>  
	    <oldCategoryId>950351</oldCategoryId>  
	    <newCategoryId>9546,9599,9599</newCategoryId>  
	</categoryId> 

</category>	

 

解决程序如下:

package com.newheight.util;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class W3CTest {


	public static void main(String[] args) throws Exception {
		String xmlFile = "file.xml";
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder db = dbf.newDocumentBuilder();

		Document domTree = db.parse(xmlFile);
		
		Element  root = domTree.getDocumentElement();
		
		showInfo(root.getNodeName());
		
		NodeList nodes = root.getElementsByTagName("categoryId");
		
		for (int i = 0; i < nodes.getLength(); i++) {
			Element categoryElement = (Element)nodes.item(i);
			NodeList childNodes = categoryElement.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				Node node = childNodes.item(j);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element childNode = (Element)node;
					showInfo(childNode.getNodeName());
					showInfo(childNode.getFirstChild().getNodeValue());
				}
			}
			
		}
	}

	public static  void showInfo(Object info) {
		System.out.println(info);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值