How to get the elements of the same name from an XML?

1

I need to get the attribute url of all elements <media:content/> of an XML similar to this one.

<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'>
    <channel>
        <item>
            <media:group>
                <media:content url='https://valor'/>
            </media:group>
        </item>
        <item>
            <media:group>
                <media:content url='https://valor'/>
            </media:group>
        </item>    
    </channel>
</rss>

This is a method that you try, but contents.getLength() returns zero.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(inputStream);
NodeList contents = doc.getElementsByTagNameNS("http://search.yahoo.com/mrss/", "content");

I tried using XPath ... again contents.getLength() returns zero.

XPathFactory factory2 = XPathFactory.newInstance();
XPath xpath = factory2.newXPath();
// XPathExpression expr = xpath.compile("//content"); 
XPathExpression expr = xpath.compile("//*[name()='content']");
NodeList contents = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

I never get the necessary nodes, any suggestions?

    
asked by rnrneverdies 01.04.2016 в 20:23
source

3 answers

2

To work with ..NS methods, when you create the DOM you must invoke the factory.setNamespaceAware(true);

method     
answered by 01.04.2016 / 21:23
source
0

To obtain the value of an attribute (in this case url), having a .rss of the form:

<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'>
    <channel>
        <item>
            <media:group>
                <media:content url='https://www.stackoverflow.com'/>
            </media:group>
        </item>
        <item>
            <media:group>
                <media:content url='https://www.cnn.com'/>
            </media:group>
        </item>
    </channel>
</rss>

You can access the elements by obtaining the list of nodes and accessing their values:

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.SAXException;
    ...
    ...

      InputStream inputStream =  url.openStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(inputStream);

        NodeList contents = doc.getElementsByTagName("item");

            for (int i = 0; i < contents.getLength(); ++i)
            {
                Element elemA = (Element) contents.item(i);
                NodeList valueListB = elemA.getElementsByTagName("media:group");
                for (int j = 0; j < valueListB.getLength(); ++j) {
                    Element elemB = (Element) valueListB.item(j);
                    NodeList valueListC = elemB.getElementsByTagName("media:content");
                    for (int k = 0; k < valueListC.getLength(); ++k)
                    {
                        Element elemC = (Element) valueListC.item(k);
                       System.out.println("url: " + elemC.getAttribute("url"));
                    }
                }
            }

Or you can go directly to the element, in this case " media:content " and get the value of its attribute " url ":

 try {
    URL   url = new URL(feedUrl);
    InputStream inputStream =  url.openStream();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(inputStream);

        NodeList contents = doc.getElementsByTagName("media:content");
        for (int i = 0; i < contents.getLength(); ++i) {
            Element elemA = (Element) contents.item(i);
            System.out.println("url: " + elemA.getAttribute("url"));
        }

    } catch (IOException e) {
       System.out.println(e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println(e.getMessage());
    }catch (SAXException e) {
        System.out.println(e.getMessage());
    }

you would get the value:

url: https://www.stackoverflow.com
url: https://www.cnn.com

    
answered by 01.04.2016 в 21:32
-2

XML:

0OK30-1-0000013-66271741VisaGoldBs50007000-200011 / 01/201511/01 / 2020ASCACamacho30-1-0000013-6111122222VisaGold $ us40002000200011 / 03/201411/01 / 2019ASCAEl Tejar

JAVA: You read XML: DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();         DocumentBuilder db = null;         String messageError = null;         Integer codResp = -1;         String msjResp="";         try {             db = dbf.newDocumentBuilder ();             InputSource is = new InputSource ();             is.setCharacterStream (new StringReader (xmlresponse));             try {                 Document document = db.parse (is);                 NodeList codeResponse = document                         .getElementsByTagName ("CodeResponse");                 NodeList messageResponse = document                         .getElementsByTagName ("MessageResponse");

            for (int i = 0; i < codigoRespuesta.getLength(); i++) {
                String codRespuesta = codigoRespuesta.item(i)
                        .getTextContent();
                codResp = Integer.parseInt(codRespuesta);
                msjResp = mensajeRespuesta.item(i).getTextContent();
            }
        } catch (SAXException e) {
            e.printStackTrace();
            if (logger.isDebugEnabled())
                logger.logDebug(messageError);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            if (logger.isDebugEnabled())
                logger.logDebug(messageError);
            return null;
        }
    } catch (ParserConfigurationException e1) {
        // handle ParserConfigurationException
        e1.printStackTrace();
        if (logger.isDebugEnabled())
            logger.logDebug(messageError);
        return null;
    }

You get the data: try {             db = dbf.newDocumentBuilder ();             InputSource is = new InputSource ();             is.setCharacterStream (new StringReader (xmlresponse));             try {                 Document document = db.parse (is);

            // NodeList listDatos =
            // doc.getElementsByTagName("DatosTarjeta");
            // for (int i = 0; i < listDatos.getLength(); i++) {
            //
            // NodeList hijos = listDatos.item(i).getChildNodes();
            // for (int j = 0; j < hijos.getLength(); j++) {
            // logger.logDebug("Datos " + i + " : "
            // + hijos.item(j).getNodeName() + ": "
            // + hijos.item(j).getTextContent());
            // }
            //
            // }

            NodeList list = document.getElementsByTagName("DatosTarjeta");
            for (int i = 0; i < list.getLength(); i++) {

                NodeList elements = list.item(i).getChildNodes();

                logger.logDebug("Datos " + i + " : "
                        + list.item(i).getTextContent());

// EVERYTHING Here you iterate where you want it to go }             } catch (SAXException e) {                 e.printStackTrace ();                 if (logger.isDebugEnabled ())                     logger.logDebug (messageError);                 return null;             } catch (IOException e) {                 e.printStackTrace ();                 if (logger.isDebugEnabled ())                     logger.logDebug (messageError);                 return null;             }         } catch (ParserConfigurationException e1) {             e1.printStackTrace ();             if (logger.isDebugEnabled ())                 logger.logDebug (messageError);             return null;         }

I hope you serve slds ...

    
answered by 29.05.2016 в 04:29