import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class NameSpaceXMLExample {
public static final void main(String[] args) {
String xmlFile="/home/localadmin/test2.xml";
try {
NameSpaceXMLExample xmlTester = new NameSpaceXMLExample(xmlFile);
}
catch (Exception e) {
System.out.println( e.getClass().getName() +": "+ e.getMessage() );
}
}
public NameSpaceXMLExample(String xmlFile) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
System.out.println("DocumentBuilderFactory: "+ factory.getClass().getName());
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
// Specify our own schema - this overrides the schemaLocation in the xml file
//factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:./test.xsd");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler( new SimpleErrorHandler() );
Document document = builder.parse(xmlFile);
String customerMakeAndModel ="";
try{
NodeList nodes = document.getElementsByTagName("ns0:Test");
Element line = (Element) nodes.item(0);
//String data = getCharacterDataFromElement(line);
if (getCharacterDataFromElement(line) != null) {
customerMakeAndModel=getCharacterDataFromElement(line);
System.out.println(customerMakeAndModel);
} else {
customerMakeAndModel="";
}
}catch(Exception e){
customerMakeAndModel="";
}
Node rootNode = document.getFirstChild();
// System.out.println("Root node: "+ rootNode.getNodeName() );
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
XML file
;ltns0:ABC xmlns:ns0="http://ABC/1.0">
;lttns0:Test<ABC;>
;lt/ns0:ABC>