对于xml文件视图:
<?xml version="1.0"?>
<EXAMPLE DATE="20160830">
<SUB NUM="1">
<NAME>Peter</NAME>
</SUB>
<SUB NUM="2">
<NAME>Mary</NAME>
</SUB>
</EXAMPLE>
在我设置NodeList以检查文档后,
我希望它可以计算每个“SUB NUM =”[x]“”中的“NAME”点击
对于我为它设置的代码:
NodeList nList= doc.getElementsByTagName("NUM"); // doc has been set correct and get successful
nList.length将返回“2”,因为xml有2个点击,命名为:“NUM”,但我想只检查每个组。
有什么想法我怎么能得到这样的长度:
SUB NUM [1]找到:[1]带有水龙头名称的长度:[NAME]
SUB NUM [2]找到:[1]长度与点击名称:[NAME]
答案 0 :(得分:0)
这可以如下完成。只是使用JAVA8语法打印hashmap。如果你不在8岁,你应该可以正常迭代并打印。
import java.io.StringReader;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class NumCountHandler extends DefaultHandler {
private HashMap<String, Integer> countOfNum = new HashMap<String, Integer>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("SUB")) {
String attributeNum = attributes.getValue("NUM");
// System.out.println("Here" + qName +"" + );
if (countOfNum.containsKey(attributeNum)) {
Integer count = countOfNum.get(attributeNum);
countOfNum.put(attributeNum, new Integer(count.intValue() + 1));
} else {
countOfNum.put(attributeNum, new Integer(1));
}
}
}
public static void main(String[] args) {
try {
String xml = "<EXAMPLE DATE=\"20160830\"> <SUB NUM=\"1\"> <NAME>Peter</NAME> </SUB> <SUB NUM=\"2\"> <NAME>Mary</NAME> </SUB></EXAMPLE>";
InputSource is = new InputSource(new StringReader(xml));
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
NumCountHandler userhandler = new NumCountHandler();
saxParser.parse(is, userhandler);
userhandler.countOfNum
.forEach((k, v) -> System.out.println("SUB NUM [" + k + "]" + "Length with tap name :[" + v + "]"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
打印
SUB NUM [1]Length with tap name :[1]
SUB NUM [2]Length with tap name :[1]