Example usage for org.w3c.dom Node TEXT_NODE

List of usage examples for org.w3c.dom Node TEXT_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node TEXT_NODE.

Prototype

short TEXT_NODE

To view the source code for org.w3c.dom Node TEXT_NODE.

Click Source Link

Document

The node is a Text node.

Usage

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("myxml.xml");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression expr = xpath.compile("//" + "item1" + "/*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Element el = (Element) nodes.item(i);
        System.out.println("tag: " + el.getNodeName());
        if (el.getFirstChild().getNodeType() == Node.TEXT_NODE)
            System.out.println("inner value:" + el.getFirstChild().getNodeValue());

        NodeList children = el.getChildNodes();
        for (int k = 0; k < children.getLength(); k++) {
            Node child = children.item(k);
            if (child.getNodeType() != Node.TEXT_NODE) {
                System.out.println("child tag: " + child.getNodeName());
                if (child.getFirstChild().getNodeType() == Node.TEXT_NODE)
                    System.out.println("inner child value:" + child.getFirstChild().getNodeValue());
            }/*from   w  ww  . j a  v  a 2s . c o m*/
        }
    }
}

From source file:ebay.Ebay.java

/**
 * @param args the command line arguments
 *///from w ww . j  a  v  a 2s . co m
public static void main(String[] args) {
    HttpClient client = null;
    HttpResponse response = null;
    BufferedReader rd = null;
    Document doc = null;
    String xml = "";
    EbayDAO<Producto> db = new EbayDAO<>(Producto.class);
    String busqueda;

    while (true) {
        busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda");
        if (busqueda != null) {
            busqueda = busqueda.replaceAll(" ", "%20");
            try {
                client = new DefaultHttpClient();
                /*
                 peticion GET
                 */
                HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems"
                        + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords="
                        + busqueda + "&siteid=0" + "&responseencoding=XML");
                /*
                 se ejecuta la peticion GET
                 */
                response = client.execute(request);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                /*
                 comienza la lectura de la respuesta a la peticion GET
                 */
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line + "\n";
                }
            } catch (IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            /*
             creamos nuestro documentBulder(documento constructor) y obtenemos 
             nuestro objeto documento apartir de documentBuilder
             */
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            Element raiz = doc.getDocumentElement();
            if (raiz == null) {
                System.exit(0);
            }
            if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) {
                NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes();
                for (int i = 0; i < array.getLength(); ++i) {
                    Node n = array.item(i);

                    if (n.getNodeType() != Node.TEXT_NODE) {
                        Producto p = new Producto();
                        if (((Element) n).getElementsByTagName("ItemID").item(0) != null)
                            p.setId(new Long(
                                    ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("EndTime").item(0) != null)
                            p.setEndtime(
                                    ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null)
                            p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ListingType").item(0) != null)
                            p.setListingtype(
                                    ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null)
                            p.setGalleryurl(
                                    ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null)
                            p.setPrimarycategoryid(new Integer(((Element) n)
                                    .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null)
                            p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("BidCount").item(0) != null)
                            p.setBidcount(new Integer(
                                    ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null)
                            p.setConvertedcurrentprice(new Double(((Element) n)
                                    .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null)
                            p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null)
                            p.setTimeleft(
                                    ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("Title").item(0) != null)
                            p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null)
                            p.setShippingservicecost(new Double(((Element) n)
                                    .getElementsByTagName("ShippingServiceCost").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ShippingType").item(0) != null)
                            p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("WatchCount").item(0) != null)
                            p.setWatchcount(new Integer(
                                    ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null)
                            p.setListedshippingservicecost(
                                    new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost")
                                            .item(0).getTextContent()));
                        try {
                            db.insert(p);
                        } catch (Exception e) {
                            db.update(p);
                        }
                    }
                }
            }
            Ventana.crear(xml);
        } else
            System.exit(0);

    }
}

From source file:DOMTreeWalkerTreeModel.java

/**
 * This main() method demonstrates the use of this class, the use of the
 * Xerces DOM parser, and the creation of a DOM Level 2 TreeWalker object.
 */// w  w w.  ja  va2s . co m
public static void main(String[] args) throws IOException, SAXException {
    // Obtain an instance of a Xerces parser to build a DOM tree.
    // Note that we are not using the JAXP API here, so this
    // code uses Apache Xerces APIs that are not standards
    DOMParser parser = new org.apache.xerces.parsers.DOMParser();

    // Get a java.io.Reader for the input XML file and
    // wrap the input file in a SAX input source
    Reader in = new BufferedReader(new FileReader(args[0]));
    InputSource input = new org.xml.sax.InputSource(in);

    // Tell the Xerces parser to parse the input source
    parser.parse(input);

    // Ask the parser to give us our DOM Document. Once we've got the DOM
    // tree, we don't have to use the Apache Xerces APIs any more; from
    // here on, we use the standard DOM APIs
    Document document = parser.getDocument();

    // If we're using a DOM Level 2 implementation, then our Document
    // object ought to implement DocumentTraversal
    DocumentTraversal traversal = (DocumentTraversal) document;

    // For this demonstration, we create a NodeFilter that filters out
    // Text nodes containing only space; these just clutter up the tree
    NodeFilter filter = new NodeFilter() {
        public short acceptNode(Node n) {
            if (n.getNodeType() == Node.TEXT_NODE) {
                // Use trim() to strip off leading and trailing space.
                // If nothing is left, then reject the node
                if (((Text) n).getData().trim().length() == 0)
                    return NodeFilter.FILTER_REJECT;
            }
            return NodeFilter.FILTER_ACCEPT;
        }
    };

    // This set of flags says to "show" all node types except comments
    int whatToShow = NodeFilter.SHOW_ALL & ~NodeFilter.SHOW_COMMENT;

    // Create a TreeWalker using the filter and the flags
    TreeWalker walker = traversal.createTreeWalker(document, whatToShow, filter, false);

    // Instantiate a TreeModel and a JTree to display it
    JTree tree = new JTree(new DOMTreeWalkerTreeModel(walker));

    // Create a frame and a scrollpane to display the tree, and pop them up
    JFrame frame = new JFrame("DOMTreeWalkerTreeModel Demo");
    frame.getContentPane().add(new JScrollPane(tree));
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    frame.setSize(500, 250);
    frame.setVisible(true);
}

From source file:Main.java

public static boolean isText(Node node) {
    return node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE;
}

From source file:Main.java

private static boolean hasOnlyOneTextNode(Node node) {
    return node.getChildNodes().getLength() == 1
            && node.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE;
}

From source file:Main.java

public static void setText(Element element, String Text) {
    Node node;/*  w ww .ja  v a  2 s  .c  o m*/
    node = element.getFirstChild();
    while (null != node) {
        if (Node.TEXT_NODE == node.getNodeType()) {
            Text text = (Text) node;
            text.setData(Text);
            return;
        }
    }
    Text text = element.getOwnerDocument().createTextNode(Text);
    element.appendChild(text);
}

From source file:Utils.java

public static String getElementText(Element e) {
    StringBuffer buf = new StringBuffer();
    for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
            buf.append(n.getNodeValue());
        }/*from w w  w  .ja va2  s .  c om*/
    }
    return buf.toString();
}

From source file:Utils.java

/**
 * Get the trimmed text content of a node or null if there is no text
 *///  w ww  . java  2  s.co  m
public static String getContent(Node n) {
    if (n == null) {
        return null;
    }
    Node n1 = getChild(n, Node.TEXT_NODE);
    if (n1 == null) {
        return null;
    }
    return n1.getNodeValue().trim();
}

From source file:Main.java

public static String getElementValue(Node elem) {
    if ((elem != null) && (elem.hasChildNodes())) {
        for (Node kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()) {
            if (kid.getNodeType() == Node.TEXT_NODE) {
                return kid.getNodeValue();
            }//w w  w.j av a 2s  . c  om
        }
    }
    return "";
}

From source file:Main.java

public static Node getFirstChildElement(Node node) {
    for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.TEXT_NODE) {
            return child;
        }//from  ww w.ja  v a  2s.  c o  m
    }

    return null;
}