我是靠谱客的博主 开心小虾米,最近开发中收集的这篇文章主要介绍Java 打印XML,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

A below xml is received:

<?xml version="1.0" encoding="UTF-8"?>

<config>

  <mobilephonedate="January 2012">

   <mode>1</mode>

   <unit>900</unit>

   <current>1</current>

   <interactive>1</interactive>

  </mobilephone>

  <mobilephonedate="February 2011">

   <mode>2</mode>

   <unit>400</unit>

   <current>2</current>

   <interactive>5</interactive>

  </mobilephone>

  <mobilephonedate="December 2013">

   <mode>9</mode>

   <unit>5</unit>

    <current>100</current>

   <interactive>3</interactive>

  </mobilephone>

</config>

Please write a java program to read and parse the xml file, outputthe mobile information.

Java 打印XML

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

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

public class parseXML {

	public static void parseXml(String fileName) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(fileName);
			NodeList nodeList = document.getChildNodes();
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node mobilePhone = nodeList.item(i);
				NodeList mobileNodeList = mobilePhone.getChildNodes();
				for (int j = 0; j < mobileNodeList.getLength(); j++) {
					Node node = mobileNodeList.item(j);
					NamedNodeMap nameNodeMap = node.getAttributes();
					for (int k = 0; nameNodeMap != null && k < nameNodeMap.getLength(); k++) {
						System.out.println(nameNodeMap.item(k).getNodeName() + ":"
								+ nameNodeMap.item(k).getTextContent());
					}
					NodeList employeeMeta = node.getChildNodes();
					for (int k = 0; employeeMeta != null
							&& k < employeeMeta.getLength(); k++) {
						System.out.println(employeeMeta.item(k).getNodeName()
								+ ":" + employeeMeta.item(k).getTextContent());
					}
				}
			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static void main(String[] args) {
		parseXml("src/config.xml");
	}
}


最后

以上就是开心小虾米为你收集整理的Java 打印XML的全部内容,希望文章能够帮你解决Java 打印XML所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部