Skip to content

Instantly share code, notes, and snippets.

@weltling
Created January 31, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weltling/da3f15d6acd23b2376097cf6c472e912 to your computer and use it in GitHub Desktop.
Save weltling/da3f15d6acd23b2376097cf6c472e912 to your computer and use it in GitHub Desktop.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class MainClass {
public static void main(String[] args) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Element book = document.createElement("book");
//book.setAttribute("xmlns:hello", "hello/world");
//book.setAttribute("hello:id", "javanut4");
// This line is equivalent to the two lines above
book.setAttributeNS("hello/world", "hello:id", "javanut4");
System.out.println("Attribute count: " + book.getAttributes().getLength());
System.out.println("Has hello:id: " + book.hasAttribute("hello:id"));
document.appendChild(book);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment