XML解析

搞一个解析工具类
public class ParseXML
{
	public static Document readXML(String path)
	{
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		Document document = null;
		try
		{
			// DOM parser instance
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			// parse an XML file into a DOM tree
			document = builder.parse(new File(path));
		} catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		} catch (SAXException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return document;
	}
}


实际解析

public Person getPersonByID(String id)
	{
		Person person = new Person(id, 0);

		// 从指定路径加载文件内容
		Document personDoc = ParseXML.readXML(XML_PATH);
		Element rootElement = personDoc.getDocumentElement();

		// 获取第一层级所有元素
		NodeList nodes = rootElement.getChildNodes();

		// 解析根节点
		for (int i = 0; i < nodes.getLength(); i++)
		{
			Node user = nodes.item(i);
			NodeList userInfo = user.getChildNodes();
			if (user.getNodeType() == Node.ELEMENT_NODE)
			{
				Element userElement = (Element) nodes.item(i);
				String personId = userElement.getAttribute("id");
				if (StringUtils.equals(personId, id))
				{
					for (int j = 0; j < userInfo.getLength(); j++)
					{
						Node userDeatil = userInfo.item(j);
						// 解析单层属性
						if (userDeatil.getNodeName() != "#text")
						{
							if (userDeatil.getNodeType() == Node.ELEMENT_NODE)
							{
								if (StringUtils.equals(userDeatil.getNodeName(), "name"))
								{
									person.setName(userDeatil.getTextContent());
								}

								if (StringUtils.equals(userDeatil.getNodeName(), "age"))
								{
									person.setAge(Integer.parseInt(userDeatil.getTextContent()));
								}
							}
						}

						NodeList userMeta = userDeatil.getChildNodes();
						for (int k = 0; k < userMeta.getLength(); k++)
						{
							Node skill = userMeta.item(k);
							if (userMeta.item(k).getNodeName() != "#text")
							{
								if (skill.getNodeType() == Node.ELEMENT_NODE)
								{
									if (StringUtils.equals(skill.getNodeName(), "skillName"))
									{
										person.setHobbit(skill.getTextContent());
									}
								}
							}
						}
					}
				}
			}

		}
		return person;
	}

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id="1">
		<name>kewen</name>
		<age>20</age>
		<skill>
			<skillName>Dota</skillName>
			<skillType>Game</skillType>
		</skill>
	</person>
	<person id="2">
		<name>kewen2</name>
		<age>20</age>
		<skill>
			<skillName>Dota2</skillName>
			<skillType>Game</skillType>
		</skill>
	</person>
	<person id="3">
		<name>kewen3</name>
		<age>20</age>
		<skill>
			<skillName>Dota3</skillName>
			<skillType>Game</skillType>
		</skill>
	</person>
</persons>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值