搞一个解析工具类
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>