SAXParseException returns null for getSystemId() - java

Why SAXParseException returns null for getSystemId()? What is System Identifier?
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class MainClass {
static public void main(String[] arg) throws Exception{
boolean validate = false;
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validate);
XMLReader reader = null;
SAXParser parser = spf.newSAXParser();
reader = parser.getXMLReader();
reader.setErrorHandler(new MyErrorHandler());
reader.parse(new InputSource(new StringReader(xmlString)));
}
static String xmlString = "<PHONEBOOK>" +
" <PERSON>" +
" <NAME>Joe Wang</NAME>" +
" <EMAIL>joe#yourserver.com</EMAIL>" +
" <TELEPHONE>202-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON> " +
"<NAME>Karol</NAE>" + // error here
" <EMAIL>karol#yourserver.com</EMAIL>" +
" <TELEPHONE>306-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON>" +
" <NAME>Green</NAME>" +
" <EMAIL>green#yourserver.com</EMAIL>" +
" <TELEPHONE>202-414-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" </PHONEBOOK>";
}
class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
show("Warning", e);
throw (e);
}
public void error(SAXParseException e) throws SAXException {
show("Error", e);
throw (e);
}
public void fatalError(SAXParseException e) throws SAXException {
show("Fatal Error", e);
throw (e);
}
private void show(String type, SAXParseException e) {
System.out.println(type + ": " + e.getMessage());
System.out.println("Line " + e.getLineNumber() + " Column "
+ e.getColumnNumber());
System.out.println("System ID: " + e.getSystemId());
System.out.println(e);
}
}

The 'system identifier' in XML is the physical location you got something from. When you just parse a string in memory, it has no system identifier at all unless you make an extra call to give it one.
You can, in this case, call InputSource.setSystemId.

The System Identifier is a URI you can specify, it's there so it can be used by the EntityResolver to decide how relative paths get resolved during xml parsing. Whether it is a physical location or just a label is up to you. Of course, in your example you don't have anything to resolve so it's not needed.

Related

handle many XML files in a directory (java)

I have managed a code to handle a file.
Now I want to use the same code to handle all the XML files which are located in a directory.
Can someone tell me how can I declare the path and how to look for a loop.
Thanks in advance
import org.xml.sax.SAXException;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.IOException;
public class XmlReadWrite3 {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("C:/Users/Desktop/1381.xml");
Element langs = doc.getDocumentElement();
Element filename= getElement(langs, "Filename");
Element beschreibung = getElement(langs, "Beschreibung");
Element name = getElement(langs, "Name");
Element ide = getElement(langs, "IDe");
System.out.println("Filename: " + filename.getTextContent() + "\n" + "Beschreibung: "
+ beschreibung.getTextContent() + "\n" + "Ersteller: " + name.getTextContent() + "\n"
+ "Pnummer: " + ide.getTextContent() + "\n\n");
}catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private static Element getElement(Element langs, String tag){
return (Element) langs.getElementsByTagName(tag).item(0);
}
}
Hi you can use the Path and File classes to loop through a directory:
import org.xml.sax.SAXException;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class XmlReadWrite3 {
public static void main(String[] args) {
// here you enter the path to your directory.
// for example: Path workDir = Paths.get("c:\\workspace\\xml-files")
Path workDir = Paths.get("path/to/dir"); // enter the path to your xml-dir
// the if checks whether the directory truly exists
if (!Files.notExists(workDir)) {
// this part stores all files withn the directory in a list
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(workDir)) {
for (Path path : directoryStream) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(path.toString());
Element langs = doc.getDocumentElement();
Element filename = getElement(langs, "Filename");
Element beschreibung = getElement(langs, "Beschreibung");
Element name = getElement(langs, "Name");
Element ide = getElement(langs, "IDe");
System.out.println("Filename: " + filename.getTextContent() + "\n" + "Beschreibung: "
+ beschreibung.getTextContent() + "\n" + "Ersteller: " + name.getTextContent() + "\n"
+ "Pnummer: " + ide.getTextContent() + "\n\n");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch (Exception e) {
System.out.println(e.getMessage())
}
}
}
private static Element getElement(Element langs, String tag) {
return (Element) langs.getElementsByTagName(tag).item(0);
}
}

Parsing and updating xml using SAX parser in java

I have an xml file with similar tags ->
<properties>
<definition>
<name>IP</name>
<description></description>
<defaultValue>10.1.1.1</defaultValue>
</definition>
<definition>
<name>Name</name>
<description></description>
<defaultValue>MyName</defaultValue>
</definition>
<definition>
<name>Environment</name>
<description></description>
<defaultValue>Production</defaultValue>
</definition>
</properties>
I want to update the default value of the definition with name : Environment.
Is it possible to do that using SAX parser?
Can you please point me to proper documentation?
So far I have parsed the document but when I update defaultValue, it updates all defaultValues. I dont know how to parse the exact default value tag.
Anything is possible with SAX, it's just waaaaay harder than it has to be. It's pretty old school and there are many easier ways to do this (JAXB, XQuery, XPath, DOM etc ).
That said lets do it with SAX.
It sounds like the problem you are having is that you are not tracking the state of your progress through the document. SAX simply works by making the callbacks when it stumbles across an event within the document
This is a fairly crude way of parsing the doc and updating the relevant node using SAX. Basically I am checking when we hit a element with the value you want to update (Environment) and setting a flag so that when we get to the contents of the defaultValue node, the characters callback lets me remove the existing value and replace it with the new value.
import java.io.StringReader;
import java.util.Arrays;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class Q26897496 extends DefaultHandler {
public static String xmlDoc = "<?xml version='1.0'?>"
+ "<properties>"
+ " <definition>"
+ " <name>IP</name>"
+ " <description></description>"
+ " <defaultValue>10.1.1.1</defaultValue>"
+ " </definition>"
+ " <definition>"
+ " <name>Name</name>"
+ " <description></description>"
+ " <defaultValue>MyName</defaultValue>"
+ " </definition>"
+ " <definition>"
+ " <name>Environment</name>"
+ " <description></description>"
+ " <defaultValue>Production</defaultValue>"
+ " </definition>"
+ "</properties>";
String elementName;
boolean mark = false;
char[] updatedDoc;
public static void main(String[] args) {
Q26897496 q = new Q26897496();
try {
q.parse();
} catch (Exception e) {
e.printStackTrace();
}
}
public Q26897496() {
}
public void parse() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xml = saxParser.getXMLReader();
xml.setContentHandler(this);
xml.parse(new InputSource(new StringReader(xmlDoc)));
System.out.println("new xml: \n" + new String(updatedDoc));
}
#Override
public void startDocument() throws SAXException {
System.out.println("starting");
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
this.elementName = localName;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value = new String(ch).substring(start, start + length);
if (elementName.equals("name")) {
if (value.equals("Environment")) {
this.mark = true;
}
}
if (elementName.equals("defaultValue") && mark == true) {
// update
String tmpDoc = new String(ch);
String leading = tmpDoc.substring(0, start);
String trailing = tmpDoc.substring(start + length, tmpDoc.length());
this.updatedDoc = (leading + "NewValueForDefaulValue" + trailing).toCharArray();
mark = false;
}
}
}

java.lang.NullPointerException :at com.mysql.jdbc.ResultSet.buildIndexMapping

I am getting the below exception in my code :
frequent i am getting this error.
java.lang.NullPointerException
at com.mysql.jdbc.ResultSet.buildIndexMapping(ResultSet.java:616)
at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:946)
at com.mysql.jdbc.ResultSet.getString(ResultSet.java:5613)
at com.sfmfm.database.DB_DashBoard.doGet(DB_DashBoard.java:275)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
for this jsp Data not loading properly. browser :firefox latest
if i am running this in eclipse its working fine.
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sfmfm.properties.efmfm;
#WebServlet("/DB_DashBoard")
public class DB_DashBoard extends DB_Conn {
/**
*
*/
private static final long serialVersionUID = -5639866791158510975L;
static Statement st,st1;
public DB_DashBoard() throws Exception {
super();
st=con.createStatement();
st1=con.createStatement();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
out=response.getWriter();
String query=request.getParameter("query");
// create a java calendar instance
//Calendar calendar = Calendar.getInstance();
// get a java.util.Date from the calendar instance.
// this date will represent the current instant, or "now".
Date now = new Date();
if(query != null && query.contains("~"))
{
System.out.println("Web Browser Request--"+query);
/*System.out.println("Today Date" +now); */
String browser_req[]=query.split("~");
if(browser_req[0].equals("Fetch_Pending_Fee"))
{
StringBuffer AllList = new StringBuffer();
try {
ResultSet rs=st1.executeQuery("SELECT sm.first_name, sm.last_name, " +
"cs.section_name, cs.class_name, sp.balance_amount, tm.first_name as tfname,tm.last_name as tlname, " +
"sm.contact_no, ft.due_date FROM teacher_master tm,student_master sm," +
" student_payment sp, class_section cs, fee_type ft, student_class sc WHERE" +
" sp.balance_amount!=0 AND sp.student_id = sm.student_id AND" +
" sm.student_id = sc.student_id AND sc.class_id = cs.class_id AND " +
"cs.class_name = ft.class_name AND tm.teacher_id = cs.teacher_id AND ft.fee_type_id=sp.payment_id AND " +
"TO_DAYS(ft.due_date) < TO_DAYS(NOW())");
if (rs != null)
{
while(rs.next())
{
AllList.append("<PENDING>");
AllList.append("<FIRSTNAME>" + rs.getString("first_name") + "</FIRSTNAME>");
AllList.append("<LASTNAME>" + rs.getString("last_name") + "</LASTNAME>");
AllList.append("<CONTACT>" + rs.getString("contact_no") + "</CONTACT>");
AllList.append("<BALANCE>" + rs.getString("balance_amount") + "</BALANCE>");
AllList.append("<DUE>" + rs.getString("due_date") + "</DUE>");
AllList.append("<SECTION>" + rs.getString("section_name") + "</SECTION>");
AllList.append("<CLASS>" + rs.getString("class_name") + "</CLASS>");
AllList.append("<TFNAME>" + rs.getString("tfname") + "</TFNAME>");
AllList.append("<TLNAME>" + rs.getString("tlname") + "</TLNAME>");
AllList.append("<SECTION>" + rs.getString("section_name") + "</SECTION>");
AllList.append("</PENDING>");
}
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("<CATALOG>" + AllList.toString() +"</CATALOG>");
System.out.println("Response sent="+"<CATALOG>" + AllList.toString()+ "</CATALOG>");
}
}
catch (Exception e)
{
System.out.println("S: Errorhai2");
e.printStackTrace();
}
}
else if(browser_req[0].equals("alert_past_info"))
{
StringBuffer AllList = new StringBuffer();
try {
ResultSet rs=st.executeQuery("SELECT DAY(date_time) AS aday, MONTHNAME(date_time) AS amonth,TIME(date_time) AS atime,title,category,sub_category,details FROM post_alert ");
if (rs != null)
{
while(rs.next())
{
AllList.append("<PASTALERT>");
AllList.append("<ADAY>" + rs.getInt("aday") + "</ADAY>");
AllList.append("<AMONTH>" + rs.getString("amonth") + "</AMONTH>");
AllList.append("<ATIME>" + rs.getInt("atime") + "</ATIME>");
AllList.append("<ATITLE>" + rs.getString("title") + "</ATITLE>");
AllList.append("<ACATA>" + rs.getString("category") + "</ACATA>");
AllList.append("<ASUB>" + rs.getString("sub_category") + "</ASUB>");
AllList.append("<ADESC>" + rs.getString("details") + "</ADESC>");
AllList.append("</PASTALERT>");
}
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("<CATALOG>" + AllList.toString() +"</CATALOG>");
System.out.println("Response sent="+"<CATALOG>" + AllList.toString()+ "</CATALOG>");
}
}
catch (Exception e)
{
System.out.println("Error On Past Alert Viewing");
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
pls provide the suggestions to clear this error.
The error you get is coming from mysql driver. Your classpath in eclipse may use a different driver version that the one you are using once your app is deployed. It probably explain why you never get this error when running in eclipse.
So I suggest you to check the driver version your are using (and probably upgrading the one you use when the app is deployed).

SaxParseException in XSD validation does not give element name

I have an xsd file and an xml file, I am validating the xml file against the xsd file using the following code
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
new InputSource(new StringReader(xsd)));
Document doc = null;
try {
DocumentBuilder parser = factory.newDocumentBuilder();
MyErrorHandler errorHandler = new MyErrorHandler();
parser.setErrorHandler(errorHandler);
doc = parser.parse(new InputSource(new StringReader(xml)));
return true;
} catch (ParserConfigurationException e) {
System.out.println("Parser not configured: " + e.getMessage());
} catch (SAXException e) {
System.out.print("Parsing XML failed due to a "
+ e.getClass().getName() + ":");
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println("IOException thrown");
e.printStackTrace();
}
return false;
MyErrorHanlder is
private static class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException spe) throws SAXException {
System.out.println("Warning: " + spe.getMessage() + " getColumnNumber is " + spe.getColumnNumber() + " getLineNumber " + spe.getLineNumber() + " getPublicId " + spe.getPublicId() + " getSystemId " + spe.getSystemId());
}
public void error(SAXParseException spe) throws SAXException {
System.out.println("Error: " + spe.getMessage() + " getColumnNumber is " + spe.getColumnNumber() + " getLineNumber " + spe.getLineNumber() + " getPublicId " + spe.getPublicId() + " getSystemId " + spe.getSystemId());
throw new SAXException("Error: " + spe.getMessage());
}
public void fatalError(SAXParseException spe) throws SAXException {
System.out.println("Fatal Error: " + spe.getMessage() + " getColumnNumber is " + spe.getColumnNumber() + " getLineNumber " + spe.getLineNumber() + " getPublicId " + spe.getPublicId() + " getSystemId " + spe.getSystemId());
throw new SAXException("Fatal Error: " + spe.getMessage());
}
}
And when the xml does not comply with xsd I get an exception.. but this exception does not have the name of the xsd element due to which this error has occured .. The message looks like
Parsing XML failed due to a org.xml.sax.SAXException:Error: cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'null'.
Instead of printing the name of the xsd element, the error message just has ''. Because of this I am not able to find and display(to the user) the exact element which is causing the error.
My xsd element looks like this
<xs:element name="FullName_FirstName">
<xs:annotation>
<xs:appinfo>
<ie:label>First Name</ie:label>
<ie:html_element>0</ie:html_element>
</xs:appinfo>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Thanks in advance
First of all, some advice. You don't need to build a DOM document just to do validation. This causes a large amount of memory overhead, maybe even running out on large input XML documents. You could just use a SAXParser. If you're using Java 1.5 or later, that isn't even necessary. From that version on, an XML validation API was included in Java SE. Check package javax.xml.validation for more info. The idea is that you first build a Schema object, then obtain a Validator from that which can be used to do validation. It accepts any Source implementation for input. Validators can also be given ErrorHandlers, so you can just reuse your class. Of course, it is possible that you actually will need a DOM, but in that case it's still better to make a Schema instance and register that with your DocumentBuilderFactory.
Now, for the actual problem. This isn't entirely easy, since the SAXParseException doesn't provide you with much context information. Your best bet is to have a ContentHandler hooked up somewhere and keep track of what element you're in, or some other positional information. You could then have that given to the error handler when needed. The class DefaultHandler or DefaultHandler2 is a convenient way of combining both error and content handling. You'll find those classes in package org.xml.sax.ext.
I've put together a test that I'll post below. Now, I do get two lines of output instead of the expected one. If this is because I'm using a Schema, or because I'm not throwing an exception and keep on processing, I'm not certain. The second line does contain the name of the element, so that might be enough. You could have some flag set on errors instead of throwing an exception and ending the parsing.
package jaxb.test;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class ValidationTest {
public static void main(String[] args) throws Exception {
//Test XML and schema
final String xml = "<?xml version=\"1.0\"?><test><test2></test2></test>";
final String schemaString =
"<?xml version=\"1.0\"?>"
+ "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"unqualified\" attributeFormDefault=\"unqualified\">"
+ "<xsd:element name=\"test\" type=\"Test\"/>"
+ "<xsd:element name=\"test2\" type=\"Test2\"/>"
+ "<xsd:complexType name=\"Test\">"
+ "<xsd:sequence>"
+ "<xsd:element ref=\"test2\" minOccurs=\"1\" maxOccurs=\"unbounded\"/>"
+ "</xsd:sequence>"
+ "</xsd:complexType>"
+ "<xsd:simpleType name=\"Test2\">"
+ "<xsd:restriction base=\"xsd:string\"><xsd:minLength value=\"1\"/></xsd:restriction>"
+ "</xsd:simpleType>"
+ "</xsd:schema>";
//Building a Schema instance
final Source schemaSource =
new StreamSource(new StringReader(schemaString));
final Schema schema =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaSource);
//Creating a SAXParser for our input XML
//First the factory
final SAXParserFactory factory = SAXParserFactory.newInstance();
//Must be namespace aware to receive element names
factory.setNamespaceAware(true);
//Setting the Schema for validation
factory.setSchema(schema);
//Now the parser itself
final SAXParser parser = factory.newSAXParser();
//Creating an instance of our special handler
final MyContentHandler handler = new MyContentHandler();
//Parsing
parser.parse(new InputSource(new StringReader(xml)), handler);
}
private static class MyContentHandler extends DefaultHandler {
private String element = "";
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(localName != null && !localName.isEmpty())
element = localName;
else
element = qName;
}
#Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println(element + ": " + exception.getMessage());
}
#Override
public void error(SAXParseException exception) throws SAXException {
System.out.println(element + ": " + exception.getMessage());
}
#Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println(element + ": " + exception.getMessage());
}
public String getElement() {
return element;
}
}
}
It's a bit rough, but you can work on from this to get what you need.

Output on namespaced xpath in java

I have the following code and have had some trouble with a specific field and it's output. The namespace is connected but doesn't seem to be outputting on the required field. Any info on this would be great.
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class test
{
public static void main(String args[])
{
String xmlStr = "<aws:UrlInfoResponse xmlns:aws=\"http://alexa.amazonaws.com/doc/2005-10-05/\">\n" +
" <aws:Response xmlns:aws=\"http://awis.amazonaws.com/doc/2005-07-11\">\n" +
" <aws:OperationRequest>\n" +
" <aws:RequestId>blah</aws:RequestId>\n" +
" </aws:OperationRequest>\n" +
" <aws:UrlInfoResult>\n" +
" <aws:Alexa>\n" +
" <aws:TrafficData>\n" +
" <aws:DataUrl type=\"canonical\">harvard.edu/</aws:DataUrl>\n" +
" <aws:Rank>1635</aws:Rank>\n" +
" </aws:TrafficData>\n" +
" </aws:Alexa>\n" +
" </aws:UrlInfoResult>\n" +
" <aws:ResponseStatus xmlns:aws=\"http://alexa.amazonaws.com/doc/2005-10-05/\">\n" +
" <aws:StatusCode>Success</aws:StatusCode>\n" +
" </aws:ResponseStatus>\n" +
" </aws:Response>\n" +
"</aws:UrlInfoResponse>";
DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
xmlFact.setNamespaceAware(true);
DocumentBuilder builder = null;
try {
builder = xmlFact.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace(); }
Document doc = null;
try {
doc = builder.parse(
new ByteArrayInputStream( xmlStr.getBytes()));
} catch (SAXException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); }
System.out.println(doc.getDocumentElement().getNamespaceURI());
System.out.println(xmlFact.isNamespaceAware());
String xpathStr = "//aws:OperationRequest";
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
String result = null;
try {
result = xpath.evaluate(xpathStr, doc);
} catch (XPathExpressionException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("XPath result is \"" + result + "\"");
}
}
namespace matching in an Xpath isn't just string matching the prefix. You have to actually define a NamespaceContext object and associate it with the xPath. It doesn't even actually matter at all if the prefixes are the same in the document and in the xPath
private NamespaceContext ns = new NamespaceContext() {
public String getNamespaceURI(String prefix) {
if (prefix.equals("ns1") return "http://alexa.amazonaws.com/doc/2005-10-05/";
else return XMLConstants.NULL_NS_URI;
}
public String getPrefix(String namespace) {
throw new UnsupportedOperationException();
}
public Iterator getPrefixes(String namespace) {
throw new UnsupportedOperationException();
}};
XPathFactory xpfactory = XPathFactory.newInstance();
XPath xpath = xpfactory.newXPath();
xpath.setNamespaceContext(ns);
String xpathStr = "//ns1:OperationRequest";
//and so on

Categories