因为回车也计算在内了(可能有方法可以去掉) 现两种方法DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("a.xml")); Element root = doc.getDocumentElement();
Node node = root.getElementsByTagName("width").item(0);
System.out.println((node.getChildNodes().getLength() - 1)/2);
//another count method
int count = 0;
for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeName().equals("size")) {
count++;
}
}
System.out.println(count);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("a.xml")); Element root = doc.getDocumentElement();
Node node = root.getElementsByTagName("width").item(0);
System.out.println((node.getChildNodes().getLength() - 1)/2);
//another count method
int count = 0;
for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeName().equals("size")) {
count++;
}
}
System.out.println(count);
Document sizes_xml = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
sizes_xml = db.newDocument();
sizes_xml = db.parse("MECsizes.xml");
Element widthElement = ((Element)sizes_xml.getDocumentElement().getElementsByTagName("width").item(0));
NodeList list = widthElement.getElementsByTagName("size");
int lents = list.getLength();
System.out.println(lents);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("a.xml")); Element root = doc.getDocumentElement();
Node node = root.getElementsByTagName("width").item(0);
System.out.println((node.getChildNodes().getLength() - 1)/2);
//another count method
int count = 0;
for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeName().equals("size")) {
count++;
}
}
System.out.println(count);
你把这句的node定义成Element类型就可以再调用getElementsByTagName方法拉,取NodeList就可以得到节点数了!
你没看懂2楼的代码吗??