(二)Java解析XML:一个简单的解析XML文件的例子

先假设有如下格式的XML文件:

<test name="test">
	<service id="create">
		<class path="d:\develop\hello.java"></class>
	</service>
	<service id="destroy">
		<class path="d:\develop\hello.java"></class>
	</service>
</test>

需要获取calss标签中名为path的节点的信息。

按照上一篇文章所讲的,首先需要创建一个Document对象:

final Logger logger = Logger.getLogger(getClass().getName());

final DocumentBuilderFactory factory = DocumentBuilderFactory
		        .newInstance();
		try
		{
			final DocumentBuilder builder = factory.newDocumentBuilder();
			logger.debug("create builder success.");
			doc = builder.parse(new File(this.path));
			logger.debug("parse xml file success");
		}
		catch (final ParserConfigurationException e)
		{
			logger.error("Constructor document builder error : " + e);
		}
		catch (final SAXException e)
		{
			logger.error("parse file error : " + e);
		}
		catch (final IOException e)
		{
			logger.error("parse file error : " + e);
		}
然后再获取元素节点:

Element root = doc.getDocumentElement();
这是一种便捷的访问XML中的文档元素的子节点的方式,此时该DOM中所有的节点都可以通过root来获取。接下来就是对XML的解析:

final NodeList nl = parent.getChildNodes();
		for (int i = 0, size = nl.getLength(); i < size; i++)
		{
			final Node node = nl.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE)
			{
				final String value = node.getAttributes().getNamedItem("id")
				        .getNodeValue();
				System.out.println(value);
			}

			for (Node index = node.getFirstChild(); index != null; index = index
			        .getNextSibling())
			{
				if (index.getNodeType() == Node.ELEMENT_NODE)
				{
					System.out.println(index.getAttributes()
					        .getNamedItem("path").getNodeValue());
				}
			}
		}
前面没有提到NodeList,NodeList接口提供对节点的有序集合的抽象,在上面的例子中,Document对象的元素的所有子节点都包含在NodeList对象nl中,即我们可以通过for循环来遍历所有的子节点。

最终的输出格式:

create
d:\develop\hello.java
destroy
d:\develop\hello.java




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值