Skip to main content

Parsing XML with namespace in Java


Introduction
Yesterday, again, I needed parser a XML stream using Java.
Then I went to Google try to find a exemple code.
Because I needed the value of two specific fields, TAGs, I decided use XPATH to get directly this values.
How ever, I needed do several tried until get a result.

Keywords
JAVA, XML, NAMESPACE, XML PARSE;

Article
I will show how to read XML without namespace and after we will read a XML streams with namespaces.

This is the first XML that I have used in this example without namespaces

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <head>
    <title>My Book</title>
  </head>
  <bookreview>
    <title>This is a book about special girls</title>
    <girls>
      <girl>
        <name>Mata Hari</name>
      </girl>
      <girl>
         <name>Belle de Jour</name>
      </girl>
      <girl>
         <name>Jeanne Bécu, comtesse du Barry</name>
      </girl>
      <girl>
         <name>Phryne</name>
      </girl>
    </girls>
  </bookreview>
</root>

I divided the code into three parts

  1. One function to read the xml file and to create an instance of an XML Document
  2. One function to create an instance XPath that provides access to the XPath evaluation environment and expressions.
  3. One function to find a value in a xml using xpath


1) One function to read the xml file and to create an instance of an XML Document

    public static Document getDocument() throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);  
        factory.setIgnoringComments(true);  
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
 
        InputStream xmlInput = XMLReader.class.getResourceAsStream("Sample.xml");
        Document doc = builder.parse(xmlInput);
        xmlInput.close();
        return doc;
    }

2) One function to create an instance XPath that provides access to the XPath evaluation environment and expressions.

    private static XPath xpath;
    public static XPath getXPath() {
        if (xpath == null) {
            XPathFactory factory = XPathFactory.newInstance();
            xpath = factory.newXPath();
        }
        return xpath;
    }

3) One function to find a value in a xml using xpath, this example: title

    private static void evaluate() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        Document doc = getDocument();
        Node base = doc.getParentNode();

        XPath xpathl = getXPath();
   
        XPathExpression expr = xpathl.compile("//title");

        base = (Node)expr.evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        if(base!=null)
            System.out.println(base.getTextContent());
        else
            System.out.println("Não Achou");
    }

Here we have full class:

package br.com.nivio.util.xml.reader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author NIVIO DOS SANTOS
 */
public class XMLReader{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            
        XMLReader.evaluate();

        } catch (XPathExpressionException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    private static void evaluate() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        Document doc = getDocument();
        Node base = doc.getParentNode();

        XPath xpathl = getXPath();
   
        XPathExpression expr = xpathl.compile("//title");

        base = (Node)expr.evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        if(base!=null)
            System.out.println(base.getTextContent());
        else
            System.out.println("Não Achou");
    }
    
    public static Document getDocument() throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);  
        factory.setIgnoringComments(true);  
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
 
        InputStream xmlInput = XMLReader.class.getResourceAsStream("Sample.xml");
        Document doc = builder.parse(xmlInput);
        xmlInput.close();
        return doc;
    }
    
    private static XPath xpath;
    public static XPath getXPath() {
        if (xpath == null) {
            XPathFactory factory = XPathFactory.newInstance();
            xpath = factory.newXPath();
        }
        return xpath;
    }
}


This is the second XML that I have used in this example with namespaces

<?xml version="1.0" encoding="UTF-8"?>
<n1:root xmlns:n1="http://www.nivio.com.br/SpecialGirls" >
  <n1:head>
    <n1:title>My Book</n1:title>
  </n1:head>
  <n1:bookreview>
    <n1:title>This is a book about special girls</n1:title>
    <n1:girls>
      <n1:girl>
        <n1:name>Mata Hari</n1:name>
      </n1:girl>
      <n1:girl>
        <n1:name>Belle de Jour</n1:name>
      </n1:girl>
      <n1:girl>
        <n1:name>Jeanne Bécu, comtesse du Barry</n1:name>
      </n1:girl>
      <n1:girl>
        <n1:name>Phryne</n1:name>
      </n1:girl>
    </n1:girls>
  </n1:bookreview>
</n1:root>

First of all we need set namespaceAware property in factory, it specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this! 

In this sample, the XML file has prefix "n1" associated to "http://www.nivio.com.br/SpecialGirls" namespace
We have no guarantees that it will always be n1 some times will be n0, nx, or any other value.

We can specify a class to redefine a prefix used in my paths. For example I have used here in xpath the prefix: myPrefix


        XPathExpression expr = xpathl.compile("//myPrefix:title");


Here we have this class:

package br.com.nivio.util.xml.reader;

import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;

public class NSContext implements NamespaceContext {

@Override
public String getNamespaceURI(String prefix) {
        return "http://www.nivio.com.br/SpecialGirls";
}

@Override
public String getPrefix(String namespaceURI) {
        return "myPrefix"; // MY PREFIX
}

@Override
public Iterator getPrefixes(String namespaceURI) {
        System.out.println("getPrefixes: namespaceURI: "+namespaceURI);
        return null;
}
}


Before compile we will set this NamespaceContext class instance to XPath object

        NamespaceContext namepspaceContext= new NSContext();
        XPath xpathl = getXPath();
        xpathl.setNamespaceContext(namepspaceContext);


Here we have full class:

package br.com.nivio.util.xml.reader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author NIVIO DOS SANTOS
 */
public class XMLReader{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            
        XMLReader.evaluate();

        } catch (XPathExpressionException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    private static void evaluate() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        Document doc = getDocument();
        Node base = doc.getParentNode();

        NamespaceContext namepspaceContext= new NSContext();
        XPath xpathl = getXPath();
        xpathl.setNamespaceContext(namepspaceContext);
   
        XPathExpression expr = xpathl.compile("//myPrefix:title");

        base = (Node)expr.evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        if(base!=null)
            System.out.println(base.getTextContent());
        else
            System.out.println("Não Achou");
    }
    
    public static Document getDocument() throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        factory.setValidating(false);  
        factory.setIgnoringComments(true);  
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
 
        InputStream xmlInput = XMLReader.class.getResourceAsStream("SampleNS.xml");
        Document doc = builder.parse(xmlInput);
        xmlInput.close();
        return doc;
    }
    
    private static XPath xpath;
    public static XPath getXPath() {
        if (xpath == null) {
            XPathFactory factory = XPathFactory.newInstance();
            xpath = factory.newXPath();
        }
        return xpath;
    }
}

Obs: Image Jean-Léon Gérôme- Esclave a vendre

Comments

Popular posts from this blog

CÓDIGOS UNICODE PARA CARACTERES ESPECIAIS

A/a á \u00e1 à \u00e0 â \u00e2 ã \u00e3 ä \u00e4 Á \u00c1 À \u00c0 Â \u00c2 Ã \u00c3 Ä \u00c4 E/e é \u00e9 è \u00e8 ê \u00ea ê \u00ea É \u00c9 È \u00c8 Ê \u00ca Ë \u00cb I/i í \u00ed ì \u00ec î \u00ee ï \u00ef Í \u00cd Ì \u00cc Î \u00ce Ï \u00cf O/o ó \u00f3 ò \u00f2 ô \u00f4 õ \u00f5 ö \u00f6 Ó \u00d3 Ò \u00d2 Ô \u00d4 Õ \u00d5 Ö \u00d6 U/u ú \u00fa ù \u00f9 û \u00fb ü \u00fc Ú \u00da Ù \u00d9 Û \u00db Consoantes ç \u00e7 Ç \u00c7 ñ \u00f1 Ñ \u00d1 Símbolos & \u0026 ' \u0027 Ʃ \u01a9 ° \u00b0 ª \u00aa ° \u00b0 ➕ \u2795 ➖ \u2796 ➗ \u2797 ✓ \u2713 ✗ \u2717

Neurônio Artificial Conceito

Outro dia conversando sobre redes neurais, consciência, inteligência artificial, percebi que estamos tão cercados e acostumados com tecnologia que em muitos cenários já estamos vivenciando a “Era da magia” onde as coisas funcionam mas o conhecimento de como funcionam está se perdendo. As máquinas acabam nos passando a sensação de serem seres vivos, simulando inteligência e comportamentos. Esta postagem descreve o conceito de um neurônio artificial para dar uma base às próximas postagens, porém com uma abordagem mais palpável, sem usar chips, transistores, ou outros elementos tecnológicos que fogem do conhecimento comum. O modelo aqui apresentado é um exercício mental, conceitual, fazendo uma série de simplificações e removendo elementos que só tornariam a visualização mais complexa. Para entender o exemplo descrevo aqui dois elementos: Relé, é um interruptor eletromecânico. A alavanca de contato se movimenta e fecha o circuito quando uma corrente elétrica percorre as espi