现在的位置: 首页 > 综合 > 正文

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

2013年10月06日 ⁄ 综合 ⁄ 共 1489字 ⁄ 字号 评论关闭

先假设有如下格式的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

抱歉!评论已关闭.