当前位置: 首页 > 工具软件 > JAXP > 使用案例 >

java jaxp_java中使用JAXP解析xml

潘安邦
2023-12-01

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /**  * 使用JAXP读取XML  *   * @author yuekun  *   */ public class Demo3 { public static void main(String[] args) { try { // 获取java.xml.parsers.DocumentBuilder类:为加载和分析XML文档提供接口,也就是XML分析程序接口 DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // 加载和分析XML文档,如果加载成功则返回一个org.w3c.dom.Document对象 Document document = builder.parse("src/1.xml"); NodeList nodeList = document.getElementsByTagName("*"); NamedNodeMap attributes = null; //下面是开始遍历NodeList集合 for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); String str = null; if (childNode instanceof Element) { Element child = (Element) childNode; if (child.getChildNodes().getLength() > 1) { str = "Element :" + child.getTagName() + ";"; } else { str = "Element :" + child.getTagName(); str += " : " + child.getFirstChild().getNodeValue() + "  "; } attributes = child.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attr = attributes.item(j); if (attr instanceof Attr) { String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); str += "  Attribute " + attrName + " : " + attrValue + ";"; } } System.out.println(str); } } } catch (Exception e) { e.printStackTrace(); } } }

 类似资料: