Java se对解析操作xml的支持及简单应用
在《数据迁移》中迁移的一个核心处理是解析并更新本地xml文件,而这种操作简单利用java API即可完成。在 javax.xml.parsers包中提供了处理xml文件的类,使用它们我们可以将xml文件读入内存; javax.xml.transform包中提供了一些转换工具,我们可以将一种源树形转化为目标树形结果,例如我们可以将dom型源转化为InputStream型,这样可以将内存中的xml文件存储在硬盘上;而在org.w3c.dom中提供了JAVA处理XML的DOM接口,可以帮助我们获取相应结点,创建结点,处理节点属性等等操作。
利用javax.xml.parsers包中,将xml文件的inputstream解析成Document,代码如下:
import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;//获取指定结点的相应结点名称的结点值 public String getNodeValue(Node parentNode, String nodeName) { String s = ""; if (parentNode.getNodeType() == Node.ELEMENT_NODE) { Element rootElement = (Element) parentNode; NodeList childList = rootElement.getElementsByTagName(nodeName); Element childElement = (Element) childList.item(0); if (childElement != null) { NodeList textFNList = childElement.getChildNodes(); if (textFNList != null) { Node temp = (Node) textFNList.item(0); if (temp != null) { s = temp.getNodeValue(); if (s != null) s = s.trim(); } } } } return s; }//获取指定结点的子节点public NodeList getNodeList(Node node) { NodeList nodeList = node.getChildNodes(); return nodeList;}//获取指定结点名称的结点public Node getNodeByTagName(Node parentNode, String tagName) { Element rootElement = (Element) parentNode; NodeList nodeList = rootElement.getElementsByTagName(tagName); if (nodeList.getLength() > 0) return nodeList.item(0); else return null;}//获取指定结点名称的结点列表public NodeList getNodeListByTagName(Node parentNode, String tagName) { Element rootElement = (Element) parentNode; NodeList nodeList = rootElement.getElementsByTagName(tagName); return nodeList;}//获取指定属性值public String getNodeAttribute(Node node, String attName) { Element elem = (Element) node; return elem.getAttribute(attName);}//创建结点并设置属性public Node createNode(String tagName, Map<String, String> attributeMap) { Element element = doc.createElement(tagName); if (attributeMap != null && !attributeMap.isEmpty()) { Iterator<Entry<String, String>> it = attributeMap.entrySet() .iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); element.setAttribute(entry.getKey(), entry.getValue()); } } return element; }
本文简单介绍了java se中操作xml的包和类,并在此基础上提供了解析和转化inputstream以及操作结点和结点属性的方法,为日后简单操作xml而不仅是依赖第三方工具包做了示范。
- 3楼lfsfxy9昨天 19:52
- 总结很到位啊。n学习了。
- 2楼llhhyy1989前天 22:59
- getNodeValue等这些方法已经封装好了吧。解析肯定有相应的解析器吧。嘻嘻,sax或stax很好用。我个人认为知道转化成Document,一切就好办了。
- 1楼lfmilaoshi3天前 21:33
- 积累呀,,加油吧n米老师