Step By Step(Java XML篇) (一)

2014-11-24 03:19:38 · 作者: · 浏览: 0

Java主要提供了三种XML的解析和节点遍历模型,它们分别是DOM(最常用)、SAX(最高效)和XPath(最直接)。我们这里主要是通过实例的方式一步一步来了解其中主要的两种模型DOM和XPath。

1. 最简单的XML:

1 //1. 这个例子是通过Element的TagName(标签名)来直接获取元素对象实例的。

2 //然后再通过该Element访问其包含的数据。

3 //2. 这个例子中都被称为Element。

4 //3. "I am the first Node"和"I am the second Node"被称为Text。

5 //文件Test.xml的样例数据

6 //

7 // I am the first Node

8 // I am the second Node

9 //

10 public static void main(String[] args) {

11 // 取得DocmentBuilderFactory对象

12 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

13 // 取得DocumentBuilder对象

14 DocumentBuilder builder = null;

15 try {

16 builder = factory.newDocumentBuilder();

17 } catch (ParserConfigurationException e) {

18 }

19 // 取得Document对象

20 Document doc = null;

21 try {

22 doc = builder.parse(new File("D:/test.xml"));

23 } catch (SAXException e) {

24 } catch (IOException e) {

25 }

26

27 NodeList nl = doc.getElementsByTagName("RootElement");

28 for (int i = 0; i < nl.getLength(); i++) {

29 Element e = (Element) nl.item(i);

30 System.out.println(e.getElementsByTagName("FirstElement").item(0)

31 .getFirstChild().getNodeva lue());

32 System.out.println(e.getElementsByTagName("SecondElement")

33 .item(0).getFirstChild().getNodeva lue());

34 }

35 }

36 //1. 没有再通过指定标签名这种特化的方式获取Element节点,而是通过一种

37 //更为泛化的方式去获取Element节点下的子节点,这种方式和普通树的遍历

38 //极为相似。

39 //2. 尽管同为Node节点(Node的实现类),但是仍然可以通过node.getNodeType()

40 //函数获的Node节点的类型,如Node.ELEMENT_NODE、Node.ATTRIBUTE_NODE等。

41 //文件Test.xml的样例数据

42 //

43 // I am the first Node

44 // I am the second Node

45 //

46 public static void main(String[] args) {

47 String filename = "D:/Test.xml";

48 try {

49 System.out.println(filename + " elementCount: " + getElementCount(filename));

50 } catch (Exception e) {

51 }

52 }

53 /* 调用getElementCount(Node),Node是节点*/

54 public static int getElementCount(String fileName) throws Exception {

55 Node node = readFile(new File(fileName));

56 return getElementCount(node); // 统计Elements

57 }

58 /* 解析文档,返回Document */

59 public static Document readFile(File file) throws Exception {

60 Document doc;

61 try {

62 /* 首先获得一个DocumentBuilderFactory 的实例*/

63 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

64 /* 创建一个DocumentBuilder 的实例*/

65 DocumentBuilder db = dbf.newDocumentBuilder();

66 /* 解析文档*/

67 doc = db.parse(file);

68 /* 返回一个Document 实例*/

69 return doc;

70 } catch (SAXParseException ex) {

71 throw (ex);

72 } catch (SAXException ex) {

73 Exception x = ex.getException(); // get underlying Exception

74 throw ((x == null) ex : x);

75 }

76 }

77 /*

78 * 使用DOM方法来统计ELEMENTS

79 */

80 public static int getElementCount(Node node) {

81 /* 如果node为空的话,然回0 */

82 if (null == node)

83