A002

PRACTICE 1 :

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class Main {

    public static void main(String[] args) {

        try {

            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

            Node doc = db.parse("src\\set6\\bookstore.xml");

            viewAllBookstore(doc);

        } catch (Exception e) {

            System.out.println(e.getMessage());

        }

    }

    private static void viewAllBookstore(Node doc) {

        try {

            if (doc.getNodeName().equals("book")) {

                String str = doc.getAttributes().getNamedItem("category").getNodeValue();

                System.out.println("book title is :" + str);

            }

            if (doc.getNodeName().equals("title")) {

                String str = doc.getAttributes().getNamedItem("lang").getNodeValue();

                System.out.println("\tlanguage is: " + str + "

\ttitle:" + doc.getTextContent());

            }

            if (doc.getNodeName().equals("author")) {

                System.out.println("\tauthor :" + doc.getTextContent());

            }

            if (doc.getNodeName().equals("year")) {

                System.out.println("\tyear :" + doc.getTextContent());

            }

            if (doc.getNodeName().equals("price")) {

                System.out.println("\tprice :" + doc.getTextContent());

                System.out.println();

            }

            NodeList children = doc.getChildNodes();

            int i = 0;

            while (i < children.getLength()) {

                viewAllBookstore(children.item(i++));

            }

        } catch (Exception e) {

            System.out.println(e.getMessage());

        }

    }

}

PRACTICE 2 :

import java.io.File;

import nu.xom.Builder;

import nu.xom.Document;

import nu.xom.Node;

import nu.xom.Nodes;

import nux.xom.xquery.XQueryUtil;

public class Main {

    public static void main(String[] args) {

        searchName("Abc");

    }

    private static void searchName(String name) {

        try {

            File f = new File("src\\set1\\toy.xml");

            Builder bd = new Builder();

            Document doc = bd.build(f);

            Nodes node = XQueryUtil.xquery(doc, "//ListToy/Toy[Name='" + name + "']");

            for (int i = 0; i < node.size(); i++) {

                Node node1 = node.get(i);

                System.out.println("Toy List is:" + node1.getValue());

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Bạn đang đọc truyện trên: truyentop.pro

Tags: