[英]Parsing XML, skip certain tags
I am following mkyong's great tutorial on how to parse xml in Java, but I have a situation where I need to read certain tags but only within an area. 我正在关注mkyong的精彩教程 ,该教程介绍了如何在Java中解析xml,但遇到一种情况,我需要读取某些标签,但只能在一个区域内读取。 eg
例如
<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
<changes>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<old_salary>175000</salary>
<new_salary>200000</salary>
</staff>
</changes>
</company>
In the tutorial it uses NodeList nList = doc.getElementsByTagName("staff");
在本教程中,它使用
NodeList nList = doc.getElementsByTagName("staff");
but this retrieves all of the staff, including the one under <changes>
. 但这会检索所有人员,包括
<changes>
下的人员。 How can I disregard all <staff>
tags under <changes>
? 如何忽略
<changes>
下的所有<staff>
标签?
Thanks 谢谢
Using DOM parser is not the best for your need. 使用DOM解析器并非最适合您的需求。 Using XPath queries should be better.
使用XPath查询应该更好。 ( API )
( API )
For exemple : 举个例子 :
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("test.xml"));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/company/staff";
//read a nodelist using xpath
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
When you are applying the items that you are intending to save you can attempt to catch it if it is under changes and then ignore it. 当您应用要保存的项目时,如果它正在更改,则可以尝试捕获它,然后将其忽略。 ex
前
if(company.changes != null)
{
//skip saving this node
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.