Step By Step(Java XML篇) (六)

2014-11-24 03:19:38 · 作者: · 浏览: 12
attribute.");

16 attr.appendChild(subAttr);

17 //给Element添加属性数据

18 attr.setAttribute("attrFirstName", "attrFirstValue");

19 root.appendChild(attr);

20 output(xmldoc, null);

21 output(xmldoc, "D:/Test1_Edited.xml");

22 //通过xpath查找某个节点都是输出找到的子节点。

23 attr = (Element)selectSingleNode("/attributes/attribute3",root);

24 //修改找到节点的其中一个属性

25 attr.getAttributeNode("name").setNodeva lue("Hello");

26 output(attr,null);

27 root.getElementsByTagName("attribute3").item(1).setTextContent("This is other test");

28 output(root,null);

29 //删除其中一个子节点

30 root.removeChild(root.getElementsByTagName("attributeWithText").item(0));

31 output(root,null);

32 //通过xpath方式获取一组节点,之后在逐个删除

33 NodeList attrs = selectNodes("/attributes/attribute3", root);

34 for (int i = 0; i < attrs.getLength(); ++i)

35 attrs.item(i).getParentNode().removeChild(attrs.item(i));

36 root.normalize();

37 output(root,null);

38 } catch (ParserConfigurationException e) {

39 } catch (SAXException e) {

40 } catch (IOException e) {

41 }

42 }

43

44 public static void output(Node node, String filename) {

45 TransformerFactory transFactory = TransformerFactory.newInstance();

46 try {

47 Transformer transformer = transFactory.newTransformer();

48 // 设置各种输出属性 www.2cto.com

49 transformer.setOutputProperty("encoding", "gb2312");

50 transformer.setOutputProperty("indent", "yes");

51 DOMSource source = new DOMSource();

52 // 将待转换输出节点赋值给DOM源模型的持有者(holder)

53 source.setNode(node);

54 StreamResult result = new StreamResult();

55 if (filename == null) {

56 // 设置标准输出流为transformer的底层输出目标

57 result.setOutputStream(System.out);

58 } else {

59 result.setOutputStream(new FileOutputStream(filename));

60 }

61 // 执行转换从源模型到控制台输出流

62 transformer.transform(source, result);

63 } catch (TransformerConfigurationException e) {

64 } catch (TransformerException e) {

65 } catch (FileNotFoundException e) {

66 }

67 }

68

69 public static Node selectSingleNode(String express, Object source) {

70 Node result = null;

71 XPathFactory xpathFactory = XPathFactory.newInstance();

72 XPath xpath = xpathFactory.newXPath();

73 try {

74 //对于只是执行单次的xpath查询,可以不通过compile而直接执行。

75 result = (Node) xpath.eva luate(express, source, XPathConstants.NODE);

76 } catch (XPathExpressionException e) {

77 }

78 return result;

79 }

80

81 public static NodeList se