Monday, 1 August 2011

Start element with namespace

      

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class MainClass{
  public static void main(String[] argsthrows XMLStreamException {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
    writer.writeStartDocument("1.0");

    writer.writeStartElement("http://www.t.com/f""sample");

    writer.writeAttribute("attribute""true");
    writer.writeAttribute("http://www.t.com/f""attribute2""false");
    writer.writeCharacters("some text");
    writer.writeCData("<test>");
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
  }
}

   
    
    
    
    
  

Attribute with Namespace

      

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

public class MainClass {
  public static void main(String[] argsthrows Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
    writer.writeStartElement("ns1""sample""http://www.e.com/ns1");
    writer.writeNamespace("ns1""http://www.e.com/ns1");

    writer.writeAttribute("http://www.e.com/ns2""attribute""true");
    writer.writeEmptyElement("http://www.e.com/ns1""inner");
    writer.writeEmptyElement("ns2""inner""http://www.e.com/ns2");
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
  }
}

   
    
    
    
    
  

Namespace Attribute Event Output 1

      
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;

public class MainClass {

  public static void main(String[] argsthrows Exception {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(System.out);

    Namespace ns1 = eventFactory.createNamespace("ns1""http://www.e.com/ns1");
    Namespace ns2 = eventFactory.createNamespace("ns2""http://www.e.com/ns2");
    List<Namespace> namespaceList = new ArrayList<Namespace>();
    namespaceList.add(ns1);
    namespaceList.add(ns2);

    Attribute attribute = eventFactory.createAttribute(ns2.getPrefix(), ns2.getNamespaceURI(),
        "attribute""true");

    writer.add(eventFactory.createStartElement(ns1.getPrefix(), ns1.getNamespaceURI()"sample",
        Collections.singletonList(attribute).iterator(), namespaceList.iterator()));
    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }

}

   
    
    
    
    
  

Namespace Attribute Event Output

      
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;

public class MainClass {

  public static void main(String[] argsthrows Exception {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(System.out);

    writer.add(eventFactory.createStartElement("ns1""http://www.e.com/ns1""sample", null,
        null));
    writer.add(eventFactory.createNamespace("ns1""http://www.e.com/ns1"));
    writer.add(eventFactory.createNamespace("ns2""http://www.e.com/ns2"));
    writer.add(eventFactory.createAttribute("ns2""http://www.e.com/ns2""attribute","true"));
    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }

}

   
    
    
    
    
  

implements NamespaceContext

 
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class MainClass {
  public static void main(String[] argsthrows Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.addNamespace("s""uri:test:schedule");
    xPath.setNamespaceContext(nsContext);

    String result = xPath.evaluate("/s:schedule/@name"new InputSource(
        new FileReader("t.xml")));
    System.out.println(result);
  }
}

class SimpleNamespaceContext implements NamespaceContext {
  private Map<String, String> urisByPrefix = new HashMap<String, String>();

  private Map<String, Set> prefixesByURI = new HashMap<String, Set>();

  public SimpleNamespaceContext() {
    addNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    addNamespace(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
  }

  public synchronized void addNamespace(String prefix, String namespaceURI) {
    urisByPrefix.put(prefix, namespaceURI);
    if (prefixesByURI.containsKey(namespaceURI)) {
      (prefixesByURI.get(namespaceURI)).add(prefix);
    else {
      Set<String> set = new HashSet<String>();
      set.add(prefix);
      prefixesByURI.put(namespaceURI, set);
    }
  }

  public String getNamespaceURI(String prefix) {
    if (prefix == null)
      throw new IllegalArgumentException("prefix cannot be null");
    if (urisByPrefix.containsKey(prefix))
      return (StringurisByPrefix.get(prefix);
    else
      return XMLConstants.NULL_NS_URI;
  }

  public String getPrefix(String namespaceURI) {
    return (StringgetPrefixes(namespaceURI).next();
  }

  public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null)
      throw new IllegalArgumentException("namespaceURI cannot be null");
    if (prefixesByURI.containsKey(namespaceURI)) {
      return ((SetprefixesByURI.get(namespaceURI)).iterator();
    else {
      return Collections.EMPTY_SET.iterator();
    }
  }

}

 

Find all elements with the name "entry" and add a child PI

  

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;

public class Main {
  public static void main(String[] argvthrows Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Element element = doc.getDocumentElement();
    ProcessingInstruction pi = doc.createProcessingInstruction("target""instruction");

    NodeList list = doc.getElementsByTagName("entry");
    for (int i = 0; i < list.getLength(); i++) {
      element = (Elementlist.item(i);
      pi = doc.createProcessingInstruction("target""instruction=" + i);
      element.appendChild(pi);
    }

  }
}

   
    
  

Adding a Processing Instruction to a DOM Document

  
import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;

public class Main {
  public static void main(String[] argvthrows Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    // Add a PI at the beginning of the document
    Element element = doc.getDocumentElement();
    ProcessingInstruction pi = doc.createProcessingInstruction("target""instruction");
    element.getParentNode().insertBefore(pi, element);


  }
}