解析xml实例

前端之家收集整理的这篇文章主要介绍了解析xml实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

自己程序中一段解析xml的代码:

private void parsePlayerXML(String path) {
  File file = new File(path);
  if (!file.exists()) {
   return;
  }
  FileInputStream inputStream = null;
  try {
   inputStream = new FileInputStream(file);
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document document = builder.parse(inputStream);
   // 获取根节点
   Element root = document.getDocumentElement();
   // 获取id,end_time;
   String id = root.getAttribute("id");
   String end_time = root.getAttribute("end_time");

   NodeList nodelist = root.getChildNodes();
   int size = nodelist.getLength();
   System.out.println("id+end_Time==="+id+"{}"+end_time);
   for (int i = 0; i < size; i++) {
    Node element = (Node) nodelist.item(i);
    if (element.getNodeName().equals("audio")) {
     String audioSrc = element.getAttributes()
       .getNamedItem("src").getNodeValue();
     System.out.println("audioSrc="+audioSrc);
    } else if (element.getNodeName().equals("pages")) {
     NodeList spanList = element.getChildNodes();
     Node node = null;
     for (int j = 0; j < spanList.getLength(); j++) {
      node = spanList.item(j);
      if (node.getNodeName().equals("page")) {
       System.out.println(node.getAttributes().getNamedItem("in").getNodeValue());
      }
     }
    }
   }

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

猜你在找的XML相关文章