Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Main {
    public static void main(String[] args) throws Exception {
        String xml = "<xml xmlns:log='http://sample.com'><test log:writer='someWriter'/></xml>";
        StringReader xmlReader = new StringReader(xml);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(xmlReader));

        Element currentNode = (Element) doc.getElementsByTagName("test").item(0);
        String attributeValue = currentNode.getAttributes().getNamedItemNS("http://sample.com", "writer")
                .getNodeValue();
        System.out.println("Attribute value is " + attributeValue);
        xmlReader.close();
    }
}