精品文档
答案: 不是。
在XML文件中,属性是标记信息的补充描述,不是标记的子标记。所以,在DOM中Attr对象是包含在Element对象中的,不是Element节点的子节点。要获得Element节点的Attr节点需要Element节点调用getAttribute()方法,该方法返回一个NamedNodeMap对象,NamedNodeMap对象由节点组成,这些节点可以转换为Attr节点。 3.有如下XML代码段:
可以通过哪些方法获得标记
第一种方法:获得Element节点“element”,通过Node接口的getTextContent()方法获得“element”节点的文本数据。
第二种方法:获得Element节点“element”的子节点,即Text类型节点,通过Text节点的getWholeText()方法获得文本数据。
4.编写Java程序,解析如下的XML文件,要求输出的结果如图8-12所示。
图8-12 程序运行结果 答案: 精品文档
精品文档
import org.w3c.dom.*;
import javax.xml.parsers.*; public class xiti4 {
public static void main(String[] args) { int n = 0;
float mathscore = 0; float englishscore = 0; float totalmath = 0; float totaleng = 0; try {
DocumentBuilderFactory factory DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(\ System.out.println(\成绩单=====\
NodeList nodeList = document.getElementsByTagName(\ for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i);
NodeList cNodeList = node.getChildNodes();
System.out.print(cNodeList.item(0).getTextContent()); for (int j = 0; j < cNodeList.getLength(); j++) { Node cNode = cNodeList.item(j);
if (cNode.getNodeType() == Node.ELEMENT_NODE) { String nodeName = cNode.getNodeName(); if (nodeName == \
System.out.print(nodeName+\:\ mathscore Float.parseFloat(cNode.getTextContent());
totalmath += mathscore;
System.out.println(mathscore); }
if (nodeName == \
System.out.print(nodeName+\:\
englishscore Float.parseFloat(cNode.getTextContent());
totaleng += englishscore;
System.out.println(englishscore); 精品文档
=
=
=
精品文档
n++;
System.out.println(\总\分
:
}
精品文档
} } } } System.out.println(\平均分=====\ System.out.println(\:\ System.out.println(\:\ } catch (Exception e) { e.printStackTrace(); } }
相关推荐: