Example usage for org.w3c.dom NodeList item

List of usage examples for org.w3c.dom NodeList item

Introduction

In this page you can find the example usage for org.w3c.dom NodeList item.

Prototype

public Node item(int index);

Source Link

Document

Returns the indexth item in the collection.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    String xml = "<metadata><codes class = 'class1'>" + "<code code='ABC'>" + "<detail x='blah blah'/>"
            + "</code>" + "</codes>" + "<codes class = 'class2'>" + "<code code = '123'>"
            + "<detail x='blah blah'/></code></codes></metadata>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength() > 0 ? "Yes" : "No");
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("nodes: " + nodes.item(i).getNodeValue());
    }/*from  w  w  w .  ja v a 2s .  c om*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);// w w w . j  a v  a 2s  .c o  m
    DocumentBuilder db = dbf.newDocumentBuilder();

    File file1 = new File("input1.xml");
    Document doc1 = db.parse(file1);
    Element rootElement1 = doc1.getDocumentElement();

    File file2 = new File("input2.xml");
    Document doc2 = db.parse(file2);
    Element rootElement2 = doc2.getDocumentElement();

    // Copy Child Nodes
    NodeList childNodes2 = rootElement2.getChildNodes();
    for (int x = 0; x < childNodes2.getLength(); x++) {
        Node importedNode = doc1.importNode(childNodes2.item(x), true);
        if (importedNode.getNodeType() == Node.ELEMENT_NODE) {
            Element importedElement = (Element) importedNode;
            // Copy Attributes
            NamedNodeMap namedNodeMap2 = rootElement2.getAttributes();
            for (int y = 0; y < namedNodeMap2.getLength(); y++) {
                Attr importedAttr = (Attr) doc1.importNode(namedNodeMap2.item(y), true);
                importedElement.setAttributeNodeNS(importedAttr);
            }
        }
        rootElement1.appendChild(importedNode);
    }

    // Output Document
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    DOMSource source = new DOMSource(doc1);
    StreamResult result = new StreamResult(System.out);
    t.transform(source, result);
}

From source file:Main.java

public static void main(String argv[]) throws Exception {
    String next = "keyword,123";
    String[] input = next.split(",");

    String textToFind = input[0].replace("'", "\\'"); // "CEO";
    String textToReplace = input[1].replace("'", "\\'"); // "Chief Executive Officer";
    String filepath = "root.xml";
    String fileToBeSaved = "root2.xml";

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);

    XPath xpath = XPathFactory.newInstance().newXPath();
    // change ELEMENTS

    String xPathExpression = "//*[text()='" + textToFind + "']";
    NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, doc, XPathConstants.NODESET);

    for (int idx = 0; idx < nodes.getLength(); idx++) {
        nodes.item(idx).setTextContent(textToReplace);
    }/*from  w ww  .  ja  v a  2  s.c om*/

    // change ATTRIBUTES
    String xPathExpressionAttr = "//*/@*[.='" + textToFind + "']";
    NodeList nodesAttr = (NodeList) xpath.evaluate(xPathExpressionAttr, doc, XPathConstants.NODESET);

    for (int i = 0; i < nodesAttr.getLength(); i++) {
        nodesAttr.item(i).setTextContent(textToReplace);
    }
    System.out.println("Everything replaced.");

    // save xml file back
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(fileToBeSaved));
    transformer.transform(source, result);
}

From source file:MainClass.java

public static void main(String[] args)
        throws IOException, ParserConfigurationException, org.xml.sax.SAXException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);// w ww  . java 2 s .  c o  m
    factory.setCoalescing(true); // Convert CDATA to Text nodes
    factory.setNamespaceAware(false); // No namespaces: this is default
    factory.setValidating(false); // Don't validate DTD: also default

    DocumentBuilder parser = factory.newDocumentBuilder();

    Document document = parser.parse(new File(args[0]));

    NodeList sections = document.getElementsByTagName("sect1");
    int numSections = sections.getLength();
    for (int i = 0; i < numSections; i++) {
        Element section = (Element) sections.item(i); // A <sect1>

        Node title = section.getFirstChild();
        while (title != null && title.getNodeType() != Node.ELEMENT_NODE)
            title = title.getNextSibling();

        if (title != null)
            System.out.println(title.getFirstChild().getNodeValue());
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(new File("src/file.xml"));
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc1 = builder.parse(fileInputStream);
    doc1.getDocumentElement().normalize();
    NodeList kList1 = doc1.getElementsByTagName("item");

    StringBuilder stringBuilder = new StringBuilder();

    for (int temp = 0; temp < kList1.getLength(); temp++) {
        Node kNode1 = kList1.item(temp);
        System.out.println("\nCurrent Element :" + kNode1.getNodeName());
        if (kNode1.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) kNode1;
            System.out.println("node name" + eElement.getNodeName());
            Node in = eElement.getFirstChild();
            if ((in.getTextContent() != null) && !(in.getTextContent()).isEmpty()
                    && !(in.getTextContent().length() == 0))
                stringBuilder.append(in.getTextContent());
        }/*from  www.j a v  a2s.c o m*/
    }
    System.out.println(stringBuilder);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from  w w w  .  j  a  v  a 2 s.  c om*/
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse("yourFile.xml");
    Element rootElement = doc.getDocumentElement();
    NodeList children = rootElement.getChildNodes();
    Node current = null;
    int count = children.getLength();
    for (int i = 0; i < count; i++) {
        current = children.item(i);
        if (current.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) current;
            if (element.getTagName().equalsIgnoreCase("tableOfContents")) {
                // Get the list of <tocEntry> items
                NodeList tocitems = element.getElementsByTagName("tocEntry");
                // Obtain a reference to the second one
                Node secondChild = tocitems.item(1);
                // Create a new <tocEntry> element
                Element newTOCItem = doc.createElement("tocEntry");
                // Create a new "Help" text node
                Text newText = doc.createTextNode("Help");
                // Make it a child of the new <tocEntry> element
                // <tocEntry>Help</tocEntry>
                newTOCItem.appendChild(newText);
                // Add the new <tocEntry> element to <tableOfContents>
                element.insertBefore(newTOCItem, secondChild);
            }
        }
    }

    System.out.println(doc.getDocumentElement());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xPath = xpf.newXPath();
    XPathExpression schoolNameExpression = xPath.compile("SchoolName");
    XPathExpression classNameExpression = xPath.compile("Classes/Class/ClassName");

    InputSource inputSource = new InputSource("input.xml");
    NodeList schoolNodes = (NodeList) xPath.evaluate("/Data/Schools/School", inputSource,
            XPathConstants.NODESET);
    for (int x = 0; x < schoolNodes.getLength(); x++) {
        Node schoolElement = schoolNodes.item(x);
        System.out.println(schoolNameExpression.evaluate(schoolElement, XPathConstants.STRING));
        NodeList classNames = (NodeList) classNameExpression.evaluate(schoolElement, XPathConstants.NODESET);
        for (int y = 0; y < classNames.getLength(); y++) {
            System.out.println(classNames.item(y).getTextContent());
        }//w  ww  .ja  va2s .co  m
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("Table.xml"));

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath path = xFactory.newXPath();
    XPathExpression exp = path.compile("/tables/table");
    NodeList nlTables = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    for (int tblIndex = 0; tblIndex < nlTables.getLength(); tblIndex++) {
        Node table = nlTables.item(tblIndex);
        Node nAtt = table.getAttributes().getNamedItem("title");
        System.out.println(nAtt.getTextContent());
        exp = path.compile("headings/heading");
        NodeList nlHeaders = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        Set<String> headers = new HashSet<String>(25);
        for (int index = 0; index < nlHeaders.getLength(); index++) {
            headers.add(nlHeaders.item(index).getTextContent().trim());
        }//from   ww  w  . j a  va  2 s  .  c  o  m
        for (String header : headers) {
            System.out.println(header);
        }
        exp = path.compile("tablebody/tablerow");
        NodeList nlRows = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        for (int index = 0; index < nlRows.getLength(); index++) {
            Node rowNode = nlRows.item(index);
            exp = path.compile("tablecell/item");
            NodeList nlValues = (NodeList) exp.evaluate(rowNode, XPathConstants.NODESET);
            List<String> values = new ArrayList<String>(25);
            for (int valueIndex = 0; valueIndex < nlValues.getLength(); valueIndex++) {
                values.add(nlValues.item(valueIndex).getTextContent().trim());
            }
            for (String value : values) {
                System.out.println(value);
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();//from   w  ww .j a  v a2  s. c  o  m

    InputSource xml = new InputSource("input.xml");
    NodeList leafNodeObjects = (NodeList) xp.evaluate("//*[not(*)]", xml, XPathConstants.NODESET);

    for (int x = 0; x < leafNodeObjects.getLength(); x++) {
        System.out.print("nodeElement = ");
        System.out.print(leafNodeObjects.item(x).getNodeName());
        System.out.print(" and node value = ");
        System.out.println(leafNodeObjects.item(x).getTextContent());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder()
            .parse("http://stackoverflow.com/feeds/tag?tagnames=java&sort=newest");
    Element root = doc.getDocumentElement();
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xPath.compile("//entry");
    NodeList nl = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " items...");
    for (int index = 0; index < nl.getLength(); index++) {
        Node node = nl.item(index);
        expression = xPath.compile("title");
        Node child = (Node) expression.evaluate(node, XPathConstants.NODE);
        System.out.println(child.getTextContent());
    }//from w w w  .j  av  a 2  s  .  c o m
}