Dom parsing -- ruturning null?
when trying to parse an xml file using DocumentBuilder.parse, i dont get any exceptions, it just returns null. I wrote a succinct Test class to debug and still cannot find the problem. below is the output, and the method i wrote.
thanx for your help:-)
matt
output looks like this:
entering Test.parse
factory = org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@7fa65e
builder = org.apache.xerces.jaxp.DocumentBuilderImpl@8385e3
doc = [#document: null]
leaving Test.parse
the parse method looks like this:
public Document parse(File xmlFile)
System.out.println("entering Test.parse");
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
Document doc = null;
try
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.parse(xmlFile);
System.out.println("factory = " + factory);
System.out.println("builder = " + builder);
System.out.println("doc = " + doc);
}//end try
catch(Exception e)
e.printStackTrace();
}//end catch e
System.out.println("leaving Test.parse");
return doc;
}//end parse
The parse() method doesn't return null, "[#document: null]" is what's returned by toString() method when you print it. Call getDocumentElement() method for the document returned by parse() to get the root node of the document.
/Sasha
when trying to parse an xml file using
DocumentBuilder.parse, i dont get any exceptions, it
just returns null. I wrote a succinct Test class to
debug and still cannot find the problem. below is the
output, and the method i wrote.
thanx for your help:-)
matt
output looks like this:
entering Test.parse
factory =
org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@7fa65
builder =
org.apache.xerces.jaxp.DocumentBuilderImpl@8385e3
doc = [#document: null]
leaving Test.parse
the parse method looks like this:
public Document parse(File xmlFile)
System.out.println("entering Test.parse");
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
Document doc = null;
try
factory =
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.parse(xmlFile);
System.out.println("factory = " +
ctory = " + factory);
System.out.println("builder = " +
ilder = " + builder);
System.out.println("doc = " + doc);
}//end try
catch(Exception e)
e.printStackTrace();
}//end catch e
System.out.println("leaving Test.parse");
return doc;
}//end parse
Similar Messages
-
Oracle XML DOM parser - attribute values are not printing on the screen ??
Hi Everyone,
I am just trying to use oracle DOM parser to paerse one of my xml file, java file can be compiled and run agianst a xml file, But I cannot see any attribute values printing on the screen..
Appreciate if anyone can help, where I have gone wrong please?
Below is the java file:
// menna puthe DOMSample eka - duwanawa 19/12/2005
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import oracle.xml.parser.v2.*;
public class DOMSample { //public class eka ***
static public void main(String[] argv){ // main method eka ###
try {
if (argv.length != 1){
// Must pass in the name of the XML file...
System.err.println("Usage: java DOMSample filename");
System.exit(1);
// Get an instance of the parser
DOMParser parser = new DOMParser();
// Generate a URL from the filename.
URL url = createURL(argv[0]);
// Set various parser options: validation on,
// warnings shown, error stream set to stderr.
parser.setErrorStream(System.err);
parser.showWarnings(true);
// Parse the document.
parser.parse(url);
// Obtain the document.
Document doc = parser.getDocument();
// Print document elements
System.out.print("The elements are: ");
printElements(doc);
// Print document element attributes
System.out.println("The attributes of each element are: ");
printElementAttributes(doc);
catch (Exception e){
System.out.println(e.toString());
} // main method eka ###
static void printElements(Document doc) {
NodeList nl = doc.getElementsByTagName("*");
Node n;
for (int i=0; i<nl.getLength(); i++){
n = nl.item(i);
System.out.print(n.getNodeName() + " ");
System.out.println();
static void printElementAttributes(Document doc){
NodeList nl = doc.getElementsByTagName("*");
Element e;
Node n;
NamedNodeMap nnm;
String attrname;
String attrval;
int i, len;
len = nl.getLength();
for (int j=0; j < len; j++){
e = (Element)nl.item(j);
System.out.println(e.getTagName() + ":");
nnm = e.getAttributes();
if (nnm != null){
for (i=0; i<nnm.getLength(); i++){
n = nnm.item(i);
attrname = n.getNodeName();
attrval = n.getNodeValue();
System.out.print(" " + attrname + " = " + attrval);
System.out.println();
static URL createURL(String filename) { // podi 3 Start
URL url = null;
try {
url = new URL(filename);
} catch (MalformedURLException ex) { /// BBBBBB
try {
File f = new File(filename);
url = f.toURL();
} catch (MalformedURLException e) {
System.out.println("Cannot create URL for: " + filename);
System.exit(0);
} // BBBBBB
return url;
} // podi 3 End
} //public class eka ***
// End of program
output comes as below:
Isbn:
Title:
Price:
Author:
Message was edited by:
chandanalHi Chandanal,
I edited your code slightly and I was able to get the correct output.
I changed the following line:
for (int j=0; j >< len; j++)to:
for (int j=0; j < len; j++)I have included the complete source below:
// menna puthe DOMSample eka - duwanawa 19/12/2005
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import oracle.xml.parser.v2.*;
public class DOMSample {
//public class eka ***
public static void main(String[] argv) {
// main method eka ###
try {
if (argv.length != 1) {
// Must pass in the name of the XML file...
System.err.println("Usage: java DOMSample filename");
System.exit(1);
// Get an instance of the parser
DOMParser parser = new DOMParser();
// Generate a URL from the filename.
URL url = createURL(argv[0]);
// Set various parser options: validation on,
// warnings shown, error stream set to stderr.
parser.setErrorStream(System.err);
parser.showWarnings(true);
// Parse the document.
parser.parse(url);
// Obtain the document.
Document doc = parser.getDocument();
// Print document elements
System.out.print("The elements are: ");
printElements(doc);
// Print document element attributes
System.out.println("The attributes of each element are: ");
printElementAttributes(doc);
} catch (Exception e) {
System.out.println(e.toString());
// main method eka ###
static void printElements(Document doc) {
NodeList nl = doc.getElementsByTagName("*");
Node n;
for (int i = 0; i < nl.getLength(); i++) {
n = nl.item(i);
System.out.print(n.getNodeName() + " ");
System.out.println();
static void printElementAttributes(Document doc) {
NodeList nl = doc.getElementsByTagName("*");
Element e;
Node n;
NamedNodeMap nnm;
String attrname;
String attrval;
int i, len;
len = nl.getLength();
for (int j = 0; j < len; j++) {
e = (Element)nl.item(j);
System.out.println(e.getTagName() + ":");
nnm = e.getAttributes();
if (nnm != null) {
for (i = 0; i < nnm.getLength(); i++) {
n = nnm.item(i);
attrname = n.getNodeName();
attrval = n.getNodeValue();
System.out.print(" " + attrname + " = " + attrval);
System.out.println();
static URL createURL(String filename) {
// podi 3 Start
URL url = null;
try {
url = new URL(filename);
} catch (MalformedURLException ex) {
/// BBBBBB
try {
File f = new File(filename);
url = f.toURL();
} catch (MalformedURLException e) {
System.out.println("Cannot create URL for: " + filename);
System.exit(0);
// BBBBBB
return url;
// podi 3 End
} //public class eka ***-Blaise -
Parsing an xml file using xerces DOM parser
Hi
I want to parse a simple xml file using DOM parser.
The file is
<Item>
<SubItem>
<title>SubItem0</title>
<attr1>0</attr1>
<attr2>0</attr2>
<attr3>0</attr3>
</SubItem>
<SubItem>
<title>SubItem1</title>
<attr1>1</attr1>
<attr2>0</attr2>
<attr3>0</attr3>
</SubItem>
<SubItem>
<title>SubItem2</title>
<attr1>1</attr1>
<attr2>1</attr2>
<attr3>0</attr3>
<SubItem>
<title>SubItem20</title>
<attr1>2</attr1>
<attr2>1</attr2>
<attr3>0</attr3>
</SubItem>
<SubItem>
<title>SubItem21</title>
<attr1>1</attr1>
<attr2>1</attr2>
<attr3>0</attr3>
</SubItem>
</SubItem>
</Item>
I just want to parse this file and want to store the values in desired datastructures,
I am trying using DOM parser, since it gives a tree structure, which is ok in this case.
public void init()
InputReader ir =new InputReader("Habsys");
Document doc =ir.read("Habitat");
System.out.println(doc);
traverse(doc);
private void traverse(Document idoc)
NodeList lchildren=idoc.getElementsByTagName("SubItem");
for(int i=0;i<lchildren.getLength();i++)
String lgstr=lchildren.item(i).getNodeName();
if(lgstr.equals("SubItem"))
traverse(lchildren.item(i));
private void traverse (Node node) {
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE)
System.out.println ("Name :"+node.getNodeName());
if(!node.hasChildNodes())
System.out.println ("Value :"+node.getNodeValue());
NodeList children = node.getChildNodes();
if (children != null) {
for (int i=0; i< children.getLength(); i++)
traverse (children.item(i));
But I am not getting required results, a lot of values I am getting as null
Could anybody tell me how to retrieve the data from the xml file, I simply want to read data and store it in data structures. For eg, for tag Subitem with title as ' SubItem1' has attr1 as '1', attr2 as'0' and attr3 as '0'.
Thanks
GauravCheck This Sample Code....
public void amethod(){
DocumentBuilderFactory dbf = null;
DocumentBuilder docBuilder = null;
Document doc = null;
try{
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(New File("path/to/your/file"));
Node root = doc.getDocumentElement();
System.out.println("Root Node = " + root.getNodeName());
readNode(root);
}catch(FactoryConfigurationError fce){ fce.printStackTrace();
}catch(ParserConfigurationException pce){ pce.printStackTrace();
}catch(IOException ioe){ ioe.printStackTrace();
}catch(SAXException saxe){ saxe.printStackTrace();
private void readNode(Node node) {
System.out.println("Current Node = " + node.getNodeName());
readAttributes(node);
readChildren(node);
private void readAttributes(Node node) {
if (!node.hasAttributes())
return;
System.out.println("Attributes:");
NamedNodeMap attrNodes = node.getAttributes();
for (int i=0; i<attrNodes.getLength(); i++) {
Attr attr = (Attr)attrNodes.item(i);
System.out.println(attr.getNodeName() + " => " + attr.getNodeValue());
private void readChildren(Node node) {
if (!node.hasChildNodes())
return;
System.out.println("Value/s:");
NodeList childNodes = node.getChildNodes();
for (int i=0; i<childNodes.getLength(); i++) {
Node child = (Node)childNodes.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
readNode(child);
continue;
if (child.getNodeType() == Node.TEXT_NODE) {
if (child.getNodeValue()!=null)
System.out.println(child.getNodeValue()); -
DOM parsing In Applet (URgent)
Is it possible to implement DOM parsing in Applet?
I am getting classnotfoundException .
I am giving the code below. pl read the code.
Applet.(parserapplet.java)
=========================
import java.io.*;
import java.awt.*;
import java.net.*;
import java.util.*;
import java.applet.*;
import com.security.*;
// for DOM parsing ....
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
public class parserapplet extends Applet
public void init()
public void start()
try
if (Class.forName("com.ms.security.PolicyEngine") != null)
{ // required for IE
PolicyEngine.assertPermission( PermissionID.SYSTEM );
catch (Throwable cnfe)
System.out.println("Policy Engine Exception: " + cnfe);
try
String str = "<?xml
version=\"1.0\"?><html><body></body></html>";
ByteArrayInputStream bis = new
ByteArrayInputStream(str.getBytes());
System.out.println("After creating input stream");
BufferedInputStream bufIn = new BufferedInputStream(new
DataInputStream(bis));
parseXMLMessage (bufIn);
catch(Exception e){}
// Actual DOM parsing goes here.....
public void parseXMLMessage(InputStream xmlMessage)
Document document = null;
DocumentBuilder documentBuilder = null;
DocumentBuilderFactory documentBuilderFactory = null;
try
documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(xmlMessage);
System.out.println("Document node: " + document);
catch(FactoryConfigurationError fce)
System.out.println("Exception Factory configuration error " + fce);
catch(ParserConfigurationException pce)
System.out.println("Exception Parser configuration Exception " pce);
catch(SAXException saxe)
System.out.println("Exception SAX error " + saxe);
catch(Exception e)
System.out.println("Exception " + e);
Html code:
=========
<html>
<body>
<APPLET code="parserapplet.class" archive = "xalan.jar" width=0
height=0
MAYSCRIPT>
<param name=cabbase value=MyApplet.cab>
</APPLET>
</body>
</html>
I have signed the Applet using signcode utility and i have put the
parserapplet.class in the MyApplet cab file and signed it. On invoking
the html file, it request for permission, and after clicking yes, the
applet loads.Fine.
No problem upto this stage.
But after loading of the applet the following exception is thrown in
Javaconsole.
Exception:
=========
com.ms.security.SecurityExceptionEx[Host]: cannot access file
C:\WINNT\Java\lib\jaxp.properties
at com/ms/security/permissions/FileIOPermission.check
at com/ms/security/PolicyEngine.deepCheck
at com/ms/security/PolicyEngine.checkPermission
at com/ms/security/StandardSecurityManager.chk
at com/ms/security/StandardSecurityManager.checkRead
at java/io/File.exists
at javax/xml/parsers/DocumentBuilderFactory.findFactory
at javax/xml/parsers/DocumentBuilderFactory.newInstance
at parserapplet.parseXMLMessage
at parserapplet.init
at com/ms/applet/AppletPanel.securedCall0
at com/ms/applet/AppletPanel.securedCall
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.run
at java/lang/Thread.run
javax.xml.parsers.FactoryConfigurationError:
java.lang.ClassNotFoundException:
org/apache/crimson/jaxp/DocumentBuilderFactoryImpl
at javax/xml/parsers/DocumentBuilderFactory.newInstance
at parserapplet.parseXMLMessage
at parserapplet.init
at com/ms/applet/AppletPanel.securedCall0
at com/ms/applet/AppletPanel.securedCall
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.processSentEvent
at com/ms/applet/AppletPanel.run
at java/lang/Thread.run
I dont know which .jar file to archive (i tried xalan,crimson, jaxp
but which of no use). I was surprised why the security Exception is
thrown , when parsing.
I have not accessed the System files!( but it searches for
jaxp.properties file!). I think the jar file is not downloaded. How to
verify that it is downloaded in applet?
The above code is only for sample.
If anybody who knows how to correct it please mail me at:
"[email protected]" with corrected code. I want this very
urgently.
Help meeeeeeeeeeeeeeeeeeee!!!!!
Prasanna.Have you found the answer to this problem? I am having a similar problem when running the parser in an ActiveX Bean.
THanks -
Problem in parsing XML using DOM Parser.
Hi,
I am parsing an XML using DOM Parser.
When i try to get attributes of a node, i dont get in the order it is written. For Eg. This the node:
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa">
When i try to print the attribute values i should get in the order:
News, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, 202, COGN-4MNMT3, aaaa
BUT I AM GETTING IN THE ORDER:
News, 202, /website/ing_news.nsf/ViewNewsForm?OpenForm&All, aaaa, COGN-4MNMT3
Is there any way to sort this problem out?
Thanks and Regards,
AshokHi Guys,
Thanks a lot for your replies.
But i want to keep all the values as attributes only.
the XML file is as shown below:
<Menu>
<Level0 label="News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="202" uid="COGN-4MNMT3" parentid="aaaa" children="3">
<Level1 label="ING News" link="" level="1" uid="COGN-4MNN89" parentid="COGN-4MNMT3" children="3" >
<Level2 label="All ING News" link="/website/ing_news.nsf/ViewNewsForm?OpenForm&All" level="2" uid="INGD-4MVTK2" parentid="COGN-4MNN89" children="0">
</Level2>
</Level1>
</Level0>
The code i was using to get attributes is:
String strElementName = new String(node.getNodeName());
// System.out.println("strElementName:"+node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) {
int iLength = attrs.getLength();
for (int i = 0; i < iLength; i++) {
String strAttributes = (String) attrs.item(i).getNodeName();
String strValues = (String) attrs.item(i).getNodeValue();
Also is it not possible to Enforce the order using some Schema/DTD in this case?
TIA
Ashok -
Context change by DOM parsing Java Mapping in XI
Hi Team,
I would like to know that how can I handle Context Change by DOM Parser Java Mapping in XI.?
Suppose the source XML structure I have like below:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
<FileName>
<filesub>
<subname>a</subname>
<subname>b</subname>
<subname>c</subname>
</filesub>
</FileName>
<FileName>
<filesub>
<subname>d</subname>
<subname>e</subname>
<subname>f</subname>
</filesub>
</FileName>
</ns0:Header>
Where the field FileName can occur maximum thrice(0...3) but the subname field is (0....unbounded) but in the target source I would like to have as given below:
<?xml version="1.0" encoding="UTF-8" ?>
- <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
- <Header>
<FileName>a</FileName>
<FileName1>d</FileName1>
</Header>
- <Header>
<FileName>b</FileName>
<FileName1>e</FileName1>
</Header>
Header>
<FileName>c</FileName>
<FileName1>f</FileName1>
</Header>
</MT_Test4>
That means the first value from every context of the source field is forming my first and second value in my target first context.Thensecond value from every context is forming my 1st and 2nd value of my target 2nd context and finally 3rd value of every context is forming my 1st and 2nd value of my target 3rd context.Is this possible to done through DOM parsing or we have to do it by UDF only?Hi Atanu,
In my last post I gave an alogorithm to solve the mapping problem. Here is the complete program for the mapping.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
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;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
public class DOMParser1 implements StreamTransformation{
public void execute(InputStream in, OutputStream out)
throws StreamTransformationException {
try
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builderel=factory.newDocumentBuilder();
/input document in form of XML/
Document docIn=builderel.parse(in);
/document after parsing/
Document docOut=builderel.newDocument();
TransformerFactory tf=TransformerFactory.newInstance();
Transformer transform=tf.newTransformer();
Element root,child,child1=null;
Node textChild;
NodeList l;
int i,n1,j,div,k;
String s[];
root=docOut.createElement("MT_Test4");
root.setAttribute("xmlns","urn:bp:xi:hr:edm:test:100");
l=docIn.getElementsByTagName("subname");
n1=l.getLength();
s=new String[n1];
for(i=0;i<n1;++i)
s<i>=l.item(i).getFirstChild().getNodeValue();
l=docIn.getElementsByTagName("filesub");
div=l.getLength();
j=n1/div;
for(i=0,k=0;i<j;++i)
child1=docOut.createElement("Header");
root.appendChild(child1);
child=docOut.createElement("FileName");
textChild=docOut.createTextNode(s[k]);
child.appendChild(textChild);
child1.appendChild(child);
child=docOut.createElement("FileName1");
textChild=docOut.createTextNode(s [ k + j ]);
child.appendChild(textChild);
child1.appendChild(child);
++k;
docOut.appendChild(root);
transform.transform(new DOMSource(docOut), new StreamResult(out));
catch(Exception e)
e.printStackTrace();
public void setParameter(Map arg0) {
public static void main(String[] args) {
try{
DOMParser1 genFormat=new DOMParser1();
FileInputStream in=new FileInputStream("C:/Apps/my dw/sdnq/apps.xml");
FileOutputStream out=new FileOutputStream("C:/Apps/my dw/sdnq/tgt1.xml");
genFormat.execute(in,out);
catch(Exception e)
e.printStackTrace();
source -> apps.xml
<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
- <FileName>
- <filesub>
<subname>a</subname>
<subname>b</subname>
<subname>c</subname>
</filesub>
</FileName>
- <FileName>
- <filesub>
<subname>d</subname>
<subname>e</subname>
<subname>f</subname>
</filesub>
</FileName>
</ns0:Header>
target structure -> tgt1.xml
<?xml version="1.0" encoding="UTF-8" ?>
- <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
- <Header>
<FileName>a</FileName>
<FileName1>d</FileName1>
</Header>
- <Header>
<FileName>b</FileName>
<FileName1>e</FileName1>
</Header>
- <Header>
<FileName>c</FileName>
<FileName1>f</FileName1>
</Header>
</MT_Test4>
Hope this helps
one more thing in this line "textChild=docOut.createTextNode(s k + j );" somehow the the third braces one opening before k and one closing after j is missing for unknown reasons. Please correct it when you actually run this code.
regards
Anupam
Edited by: anupamsap on Mar 7, 2011 12:47 PM -
XML DOM Parsing getAttributes() in J2SE 5.0 vs. J2SE 1.4
I am experiencing the following problem, with the Node.getAttributes() function although the following code runs fine under Java 1.4, and getAttributes() returns the actual string attribute values:
File xmlFile = new File(fileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
// Begin analyzing XML
Element root = doc.getDocumentElement();
// Enumerate all children
NodeList children = root.getChildNodes();
Node rootNode = null;
NodeList nodeList = children;
for (int R = 0; R < nodeList.getLength() ; R++)
if (nodeList.item(R).getNodeType() == Node.ELEMENT_NODE)
rootNode = nodeList.item(R);
System.out.println("> " + rootNode.getNodeName() + " - " + rootNode.getAttributes().toString());
In J2SE 5.0 the Node.getAttributes() returns the following:
[email protected]d of returning then the actual attribute string (like in Java 1.4)!
If it helps at all I am using DOM parser (as noticed above, org.w3c.dom)
My assumption is that J2SE 5.0 returns an attribute map that is encoded differently then Java 1.4
Thank you for your time & appreciate any help...The getAttributes method returns a NamedNodeMap.
Iterate over the NamedNodeMap to get attribute values.
Instead of rootNode.getAttributes().toString();
NamedNodeMap map=rootNode.getAttributes().toString();
for(int i=0; i<map.getLength(); i++){
Node node=map.item(i);
if(node.getNodeType()==Node.ATTRIBUTE_NODE)
System.out.println("Attribute Node "+node.getNodeName()+ "has value "+ node.getNodeValue());
} -
XML Validation using XDK SAX/DOM Parser
Hello,
I am trying to validate xml against xsd using SAX/DOM parser, both the files are stored as CLOB column in the database. I have the requirement to report all the validation errors and based on some helpful advice/code from the earlier posts in this forum, I have used the following code to validate and report the errors.
The code works fine but for large files it never goes beyond a certain number of errors i.e. getNumMessages() (XMLParseException) never returns value greater than 100 and thus limits the output of the validation errors. Any pointers to suggest change in code or an alternative will be extremely helpful.
Datebase Version : Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED <> as package <package name>;
import java.net.*;
import java.io.*;
import java.util.*;
import java.sql.SQLException;
import oracle.sql.CLOB;
import oracle.xml.parser.schema.*;
import oracle.xml.parser.v2.*;
import org.w3c.dom.*;
public class XMLSchemaVal
public static String validate(CLOB xmlDoc, CLOB xsdDoc)
throws Exception
//Build Schema Object
XSDBuilder builder = new XSDBuilder();
Reader xsdInUnicodeFormat = xsdDoc.getCharacterStream();
XMLSchema schemadoc = (XMLSchema)builder.build(xsdInUnicodeFormat, null);
//Build XML Object
Reader xmlInUnicodeFormat = xmlDoc.getCharacterStream();
// Genereate the SAX
SAXParser saxparser_doc = new SAXParser();
// Set Schema Object for Validation
saxparser_doc.setXMLSchema(schemadoc);
saxparser_doc.setValidationMode(XMLParser.SCHEMA_VALIDATION);
saxparser_doc.setPreserveWhitespace (true);
String returnValue;
try {
saxparser_doc.parse (xmlInUnicodeFormat);
returnValue = "The input XML parsed without errors.\n";
catch (XMLParseException se) {
returnValue = "Parser Exception: ";
for (int i=0 ; i < se.getNumMessages(); i++)
returnValue += "<LN: " + se.getLineNumber(i) + ">: " + se.getMessage(i);
//returnValue = "Parser Exception: " + se.getNumMessages();
catch (Exception e) {
returnValue = "NonParserException: " + e.getMessage();
return returnValue;
Function to call the above utility from PL/SQL
CREATE OR REPLACE FUNCTION F_XMLSCHEMAVALIDATION (P_XML IN clob ,P_XSD IN clob) RETURN VARCHAR2 IS
LANGUAGE JAVA NAME XMLSchemaVal.validate(oracle.sql.CLOB,oracle.sql.CLOB) return java.lang.String';
Thanks.Got the answer !!!
NetBeans it self support generation of dtd file based on XML file.
Open XML file and right click on the code block. Select option to generate dtd file.
This is the drtd file it has generated..
<?xml version='1.0' encoding='UTF-8'?>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT book (person)*>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT person (age|last|first)*>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT first (#PCDATA)>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT last (#PCDATA)>
<!--- Put your DTDDoc comment here. -->
<!ELEMENT age (#PCDATA)> -
I am using Dom parser in java to parse xml.I am able to retrive data from xml.Can any one help me in updating an xml when data is modified in the user interface.I am created interface in html with three fields namely UserName , LastLogin, Modified fields.If Admin person wants to modify any of these three fields , those changes should reflect in xml also.
Thanks
divyaCode snippet
===========
OutputFormat outputFormat = new OutputFormat("XML","ISO-8859-1",true);
outputFormat.setDoctype(null,"emp.dtd")
It adds the DOCTYPE element but doesnt create the .DTD file.
<!DOCTYPE ROOT_EL SYSTEM "emp.dtd">
Any ideas?
Rgds,
Seetesh -
NonValidating DOM Parser & Whitespace text nodes
Hello,
Using the DOM parser and the Oracle samples (DOMSample),I wrote a
java progam to filter an XML file.
Ex:<a>
1
<c>2</c>
</a>
to
a:
b:1
c:2
end
It works fine. But when I set the parsers validation mode to
false, my code fails. It seems that a TEXTNODE is now generated
containing the whitespace of the file as I traverse the DOM tree.
Should I code around this or is there another way to handle
this unexpected textnode?
Bob
nullCorrect me if i am wrong.
The Element object you are referring to is of type
org.w3c.dom.Element.
And as far as i know, it doesn't have any methods
such as getTextContent().Even the Node class does not
have such method.Yes you are wrong , with JDK 1.5 they do have getTextContent() method for org.w3c.dom Node & Element .
@ OP , dont know why your getTextContent is not working its working over here for me .
You may iterate over such a Node and remove the contents.
for. eg.
<Name>Son</Name>
Node name //(is ur node )
NodeList nk = node.getChildNodes();
String val= null;
for (int j=0; j < nk.getLength(); j++) {
Node k = nk.item(j);
val= k.getNodeValue();
}Now u may use the value collected in String val
but make sure u apply this code only to above type of node, viz <Name>Son</Name> -
Strange Problem about Dom Parser
Hi, all
I am using Dom parser to extract content from one xml file, and it works this afternoon, then tonight when i tried to run again, it gives me an exception:
org.xml.sax.SAXParseException: Document root element "Total", must match DOCTYPE root "null".
In my xml file, i don't have <!DOCTYPE ....>, but it is the same xml file i run this afternoon, also, as far as i know, <!DOCTYPE> is not necessary, right?
Please help me, really frustrated here!The parser class only supports a class derived from the java.io.Reader class. I am not sure if there is a class that derives from such that would handle a url string. You may need to obtain the file using java.net for the url and then pass that to a FileReader object.
One thing that i just thought of that might work is this:
parser.parse(new File(url)); -
How to get nodes and its attributes of an XML file usiong DOM parsing?
how to get nodes and its attributes of an XML file usiong DOM parsing?
i am new to XML parsing.......
Thanking you........import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; ...
//Setup the document
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("MY_XML_FILE.xml"));
//get elemets by name
String elementValue = doc.getElementsByTagName("MY_ELEMENT").item(0).getTextContent();
//This method can return multiple nodes, in this instance I get item(0) , first nodeRead the api for other methods of getting data. -
Java DOM Parser (XML)
Could someone please give me a link where I can find a example of a DOM parser, w3c. That shows how to parse an xml string or file and build the tree then access parts of it? I cant find a basic example anywhere!
Check this
http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/dom/1_read.html -
Problem in parsing a xml string using dom parser
i want to parse a Xml String using a Dom parser......the parse function in dom parser takes only input stream as argument.......so i made the code as
InputStream inputstream = new StringBufferInputStream(XmlData) ;
InputSource inputSource = new InputSource(inputstream );
but saxexception is coming and also warning called
"java.io.StringBufferInputStream in java.io has been deprecated"
please help me.........i want to parse a Xml String using a Dom
parser......the parse function in dom parser takes
only input stream as argument.......This is not true of the DOM parser in Java 1.4. So you might want to get rid of your old parser and replace it by something more current. Or perhaps you are using 1.4 and you just didn't read all of the API docs. -
JmsAdapter DOM Parsing Exception handling
Hi,
I'm currently facing a problem with the behaviour of the Jms Adapter.
Whenever a JMS message is put in the queue and that message is not XML valid, the Jms Adapter (consumer) throw the exception "DOM Parsing Exception in translator Exception".
That's fine, I understand that the message was not well formed. But what is not fine is that the underlying BPEL is not instanciated : meaning I can't handle the exception properly.
Is there a way to force the Jms Adapter not to crash on the DOM Parsing for the BPEL to be instanciated (and then being able to handle the exception there) ?
Or is there a way to handle the error thrown by the Jms Adapter itself ? How ?
I think I do have a workaround to this if there is no better option (if both above questions cannot be answered) but I would rather not implement it since it will involve some extra steps / complexity.
> It would be to check the "native format opaque schema" option and then use a java embedded to decode the base64 into a string for eventually parsing it.
regards,
mathieuHi Mathieu,
The messages that error out before being posted to the service infrastructure are referred to as rejected messages. For example, the Oracle File Adapter selects a file having data in CSV format and tries to translate it to XML format (using NXSD). If there is any error in the translation, this message is rejected and are not be posted to the target composite.
You can create rejection handlers to handle message errors. Message errors include those that occur during translation, correlation ID mismatch and XML parsing after message reception.
Docs on how to do that are here...
http://docs.oracle.com/cd/E28280_01/integration.1111/e10231/life_cycle.htm#CIAIICJJ
Cheers,
Vlad
Maybe you are looking for
-
My computer is no longer working and I had hundreds of songs in my iTunes library, but when I tried to join on my laptop I couldn't get my songs, it asked me if I wanted to change computers but I'm scared in case they get deleted .
-
Macbook Pro C2D- best computer I have ever owned. -Sweetest deal ever-
Hi, I've been looking to replace an aging 12 inch 867 that I've beaten on tour for 16 months. I decided on the Macbook Pro. I first purchased a 1.83, 2 weeks ago knowing the Core 2 Duos were coming. I was tempted by a good deal ($1699.00 including Ap
-
Save PDF in KM - Personal Documents of user with Web Dynpro ABAP (WDA)
Hi Experts, I have a WebDynpro ABAP Application, running in my Portal, which generates (after some input steps) a pdf (Adobe Form) as confirmation. Of course the user can save and print the pdf-form by himself, but I would like to save the PDF automa
-
Screen flicker when running battery power?
Hi MSI Fans! Do you guys have the problem when your screen flickers very badly when running battery (unplugged)\ If mods know how to solve it, it is appreciated if you post here. Thanks a lot!
-
I installed the iPhone app and signed in, no problem. All my contacts show. I am online, reading emails, surfing Safari. I try to make a Skype call, and get this error message: "You must go online to make this call." But I AM online! I try again. Sam