The read and write java xml (DOM)

First, let's get to the Document Object

private static Document getDocument(String path) {
    //1.创建DocumentBuilderFactory对象
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //文档构建对象
    DocumentBuilder builder = null;
    try {
        //从工厂对象中获得文档构建对象
        builder = factory.newDocumentBuilder();
        //用文档构建对象创建文档  参数为xml文件地址
        Document d = builder.parse(path);
        //简写
        Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
        return d;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Then get a document tree
traversal of the document tree is mainly used these methods

  • getElementsByTagName (string tagname) // return NodeList find according to element names, also returns a length not find an empty list 0
  • getChildNodes () // Returns the current element NodeList returned all direct child elements
  • getElementById () // Returns Element Returns the element with the specified id
    as xml tag names are generally used since it is given the getElementsByTagName () would suffice
//使用getElementsByTagName获取xml元素
NodeList list= d.getElementsByTagName("Brand");
//循环读取
for (int i = 0; i < list.getLength(); i++) {
    //接收列表中的项目并转换为元素  由于NodeList的item返回Node 而Element是Node的子接口,所以可以直接转换
    Element element = (Element) list.item(i);
    //对获取到的元素进行各种操作
    //获取name属性
    String name = element.getAttribute("name");
    //删除自身
    element .getParentNode().removeChild(brand.item(i));
    //设置属性
    element.setAttribute("id", i + "");
}

Similarly, multi-level multi-cycle can only

//使用getElementsByTagName获取xml元素
NodeList list= d.getElementsByTagName("Brand");
//循环读取
for (int i = 0; i < list.getLength(); i++) {
    //接收列表中的项目并转换为元素
    Element element = (Element) list.item(i);
    ...
    //第二层
    NodeList list2= d.getElementsByTagName("Brand");
    for (int i = 0; i < list2.getLength(); i++) {
        Element element2 = (Element) list.item(i);
        ...
    }
}

Write to be updated tomorrow ....

Guess you like

Origin www.cnblogs.com/tianZiDiYiHao/p/11902022.html