java程序操作xml文件

来源:互联网 发布:不敢给客服打电话 知乎 编辑:程序博客网 时间:2024/06/06 03:09

java代码

package xmlTest;import javax.lang.model.element.Element;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XmlTest2 {public static void main(String[] args){//文件路径String filePath="/Users/apple/Downloads/dom4j-1.6.1/project.xml";DocumentBuilderFactory documentBuliderFactory=DocumentBuilderFactory.newInstance();try {DocumentBuilder documentBuilder=documentBuliderFactory.newDocumentBuilder();Document document=documentBuilder.parse(new java.io.File(filePath));NodeList nodeList=document.getElementsByTagName("dog");System.out.println(nodeList.getLength());            for (int i = 0; i < nodeList.getLength(); i++)              {                  Node dog = nodeList.item(i);                                  //输出dog节点的第一个属性(笔者实现的时候不能同dog.getAttribute(),因此只能用这种方式)                System.out.println(dog.getAttributes().item(0));                for (Node node = dog.getFirstChild(); node != null; node = node.getNextSibling())                  {                      if (node.getNodeType() == Node.ELEMENT_NODE)                      {                          String name = node.getNodeName();                        //文本实质上是node的子节点                        String value = node.getFirstChild().getNodeValue();                          System.out.print(name + ":" + value + "\t");                      }                  }                  System.out.println();              }  } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

xml文件:

<?xml version="1.0" encoding="UTF-8"?><pets>      <dogs>          <dog id="1">                        <name>YAYA</name>              <health>100</health>              <love>0</love>              <strain>酷酷的雪娜瑞</strain>          </dog>          <dog id="2">                        <name>OUOU</name>              <health>90</health>              <love>15</love>              <strain>聪明的拉布拉多犬</strain>          </dog>      </dogs>      <penguins>          <penguin id="3">                        <name>QQ</name>              <health>100</health>              <love>20</love>              <sex>Q仔</sex>                     </penguin>              </penguins>  </pets>  

运行结果:

2

id="1"

name:YAYA health:100 love:0 strain:酷酷的雪娜瑞

id="2"

name:OUOU health:90 love:15 strain:聪明的拉布拉多犬


0 0