Xml document validation using Schema
I want to validate XML Document using XML Schema...
does any body have an idea how to do it.
Every time i m running my java file by using different XML FILE AND XSD FILE in command line i m getting same error.
error is:
Exception in thread "main" org.xml.sax.SAXException: Error: URI=null Line=2: s4s-elt-schema-ns: The namespace of element 'catalog' must be from the schema name space.
at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1115)
at SAXLocalNameCount.main(SAXLocalNameCount.java:117)
Below is my java code with xml file and schema file.
plz get back to me as soon as possible it is urgent.
thanx
java File
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
import java.io.*;
public class SAXLocalNameCount extends DefaultHandler {
/** Constants used for JAXP 1.2 */
static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
/** A Hashtable with tag names as keys and Integers as values */
private Hashtable tags;
// Parser calls this once at the beginning of a document
public void startDocument() throws SAXException {
tags = new Hashtable();
// Parser calls this for each element in a document
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException
String key = localName;
Object value = tags.get(key);
if (value == null) {
// Add a new entry
tags.put(key, new Integer(1));
} else {
// Get the current count and increment it
int count = ((Integer)value).intValue();
count++;
tags.put(key, new Integer(count));
System.out.println("TOTAL NUMBER OF TAG IN FILE = "+count);
// Parser calls this once after parsing a document
public void endDocument() throws SAXException {
Enumeration e = tags.keys();
while (e.hasMoreElements()) {
String tag = (String)e.nextElement();
int count = ((Integer)tags.get(tag)).intValue();
System.out.println("Local Name \"" + tag + "\" occurs " + count
+ " times");
static public void main(String[] args) throws Exception {
String filename = null;
String schemaSource = null;
// Parse arguments
schemaSource = args[0];
filename = args[1];
// Create a JAXP SAXParserFactory and configure it
SAXParserFactory spf = SAXParserFactory.newInstance();
// Set namespaceAware to true to get a parser that corresponds to
// the default SAX2 namespace feature setting. This is necessary
// because the default value from JAXP 1.0 was defined to be false.
//spf.setNamespaceAware(true);
// Validation part 1: set whether validation is on
spf.setValidating(true);
// Create a JAXP SAXParser
SAXParser saxParser = spf.newSAXParser();
System.out.println(" saxparser "+saxParser);
// Validation part 2a: set the schema language if necessary
if (true) {
try {
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
System.out.println(" saxparser ");
} catch (SAXNotRecognizedException x) {
// This can happen if the parser does not support JAXP 1.2
System.err.println(
"Error: JAXP SAXParser property not recognized: "
+ JAXP_SCHEMA_LANGUAGE);
System.err.println(
"Check to see if parser conforms to JAXP 1.2 spec.");
System.exit(1);
// Validation part 2b: Set the schema source, if any. See the JAXP
// 1.2 maintenance update specification for more complex usages of
// this feature.
if (schemaSource != null) {
saxParser.setProperty(JAXP_SCHEMA_SOURCE, new File(schemaSource));
System.out.println(" saxparser 123");
// Get the encapsulated SAX XMLReader
XMLReader xmlReader = saxParser.getXMLReader();
System.out.println(" XML READER "+xmlReader);
// Set the ContentHandler of the XMLReader
xmlReader.setContentHandler(new SAXLocalNameCount());
System.out.println(" XML READER 345 ");
// Set an ErrorHandler before parsing
xmlReader.setErrorHandler(new MyErrorHandler(System.err));
System.out.println(" XML READER 67878 ");
// Tell the XMLReader to parse the XML document
xmlReader.parse(filename);
System.out.println(" XML READER ");
// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintStream out;
MyErrorHandler(PrintStream out) {
this.out = out;
* Returns a string describing parse exception details
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
xml file(books.xml)
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>
(books.xsd)
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="catalog">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="book" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="genre" type="xsd:string"/>
<xsd:element name="price" type="xsd:float"/>
<xsd:element name="publish_date" type="xsd:date"/>
<xsd:element name="description" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Add xmlns:xsi attribute to the root element <catalog>.
<catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='books.xsd'>
Similar Messages
-
In-memonry xml document validation against schema with xerces
Hello, there.
I found that I can't use JAXP's javax.xml.validation package with jdk 1.4. (Am I wrong?)
Anyway,
I found that I can use xerces's DOMParser for the same purpose.
But I can't find the way to validate my programmatically generate org.w3c.dom.Document against existing schema file.
Can anybody help me?
Thanks.Have you read Xerces documentation or SUN xml API, there is always a parser option (I suppose it's in the standard) to validate input while parsing.
Look the API : http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setValidating(boolean) -
Validating an XML document to a schema using ColdFusion
This is something I have never tried before. We created an XML Schema to define XML documents we expect to receive from various entities. When we receive the document, we would like to validate it before processing it. I think ColdFusion is up to this from reading the documentation, but we have not got anything working yet.
When we try and xmlParse() our test XML file against the XML schema we get the following error. When we use a web based XML validation tool and feed it the same XML file and schema it validates just fine.
An error occured while parsing an XML document.
[Error] :2:6: cvc-elt.1: Cannot find the declaration of element 'pur'.
The error occurred in D:\playground\warren\ppur_file_import.cfm: line 57
55 :
56 :
57 : <cfset xmldoc = XmlParse(ExpandPath(filepath), true, ExpandPath(validator)) />
58 : <cfdump var="#xmldoc#">
59 : <cfabort>
Searching for the error has not provided me any useful hints. Can anybody here?XML SCHEMA
<?xml version="1.0" encoding="iso-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Simple Types -->
<xs:simpleType name="RECORD_ID">
<xs:restriction base="xs:string">
<xs:pattern value="[AaBbCc]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="REPORT_MONTH">
<xs:restriction base="xs:integer">
<xs:pattern value="(0[1-9]|1[0-2])"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="REPORT_YEAR">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="MFG_FIRMNO">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{7}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="LABEL_SEQ_NO">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{5}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="REVISION_NO">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Za-z]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="REG_FIRMNO">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{7}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="GROWER_ID">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{11}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CEDTS_IND">
<xs:restriction base="xs:string">
<xs:pattern value="[Ee]|[ ]"/>
<!-- needs to match E or a blank. -->
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="APPLIC_DT">
<xs:restriction base="xs:integer">
<xs:pattern value="(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])([0-9]{2})"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="SITE_CODE">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{6}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="QUALIFY_CD">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PLANTING_SEQ">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ACRE_TREATED">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{8}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="UNIT_TREATED">
<xs:restriction base="xs:string">
<xs:pattern value="[ATSCKUPatsckup]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AMT_PRD_USED">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{10}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="UNIT_OF_MEAS">
<xs:restriction base="xs:string">
<xs:pattern value="LB|OZ|GA|QT|PT|KG|GR|LI|ML"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="DOCUMENT_NO">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{8}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="LINE_ITEM">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{4}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PROCESS_DT">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{4}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BATCH_NO">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-5][0-9][0-9][0-9]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="COUNTY_CD">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-5][0-9]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="SECTION">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="TOWNSHIP">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="TSHIP_DIR">
<xs:restriction base="xs:string">
<xs:pattern value="[NSns]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="RANGE">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="RANGE_DIR">
<xs:restriction base="xs:string">
<xs:pattern value="[EWew]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BASE_LN_MER">
<xs:restriction base="xs:string">
<xs:pattern value="[HMShms]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AER_GND_IND">
<xs:restriction base="xs:string">
<xs:pattern value="[AFGOafgo]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="SITE_LOC_ID">
<xs:restriction base="xs:string">
<xs:pattern value="[-0-9 ]+"/>
<!-- Examples in files I checked
only had numeric characters and
a dash. The county contract doesn't
specify numeric-only, so letters may
be acceptable. I find no evidence of
any letters being used. -->
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ACRE_PLANTED">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{8}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="UNIT_PLANTED">
<xs:restriction base="xs:string">
<xs:pattern value="[ATSCKUPatsckup]"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="APPLIC_TM">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{4}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="APPLIC_CNT">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{6}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="FUME_CD">
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9]{4}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="LICENSE_NO">
<xs:restriction base="xs:integer">
<xs:pattern value="[-0-9A-Za-z]{13}"/>
</xs:restriction>
</xs:simpleType>
<!-- end Simple Types -->
<!-- !!!!!!!!! Begin Abstract Types !!!!!!!!! -->
<xs:complexType name="application_data_abs" abstract="true">
<xs:sequence>
<xs:element name="GROWER_ID" type="GROWER_ID" />
<xs:element name="CEDTS_IND" type="CEDTS_IND" />
<xs:element name="APPLIC_DT" type="APPLIC_DT" />
<xs:element name="SITE_CODE" type="SITE_CODE" />
<xs:element name="QUALIFY_CD" type="QUALIFY_CD" />
<xs:element name="PLANTING_SEQ" type="PLANTING_SEQ" />
<xs:element name="ACRE_TREATED" type="ACRE_TREATED" />
<xs:element name="UNIT_TREATED" type="UNIT_TREATED" />
<xs:element name="AMT_PRD_USED" type="AMT_PRD_USED" />
<xs:element name="UNIT_OF_MEAS" type="UNIT_OF_MEAS" />
<xs:element name="DOCUMENT_NO" type="DOCUMENT_NO" />
<xs:element name="LINE_ITEM" type="LINE_ITEM" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="application_abs" abstract="true">
<xs:sequence>
<xs:element name="key_data" type="key_data" />
<xs:element name="product_data" type="product_data" />
</xs:sequence>
</xs:complexType>
<!-- !!!!!!!!! End Abstract Types !!!!!!!!! -->
<!-- !!!!!!!!! Start Complex Types !!!!!!!!! -->
<xs:complexType name="product_data">
<xs:sequence>
<xs:element name="MFG_FIRMNO" type="MFG_FIRMNO" />
<xs:element name="LABEL_SEQ_NO" type="LABEL_SEQ_NO"/>
<xs:element name="REVISION_NO" type="REVISION_NO" />
<xs:element name="REG_FIRMNO" type="REG_FIRMNO" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="key_data">
<xs:sequence>
<xs:element name="RECORD_ID" type="RECORD_ID" />
<xs:element name="COUNTY_KEY">
<!--
The optional COUNTY_ID field would be used by
the Counties to include their internal
record identifier. This would allow DPR
to reference a county's internal record ID
in the event of data inconsistencies.
-->
</xs:element>
<xs:element name="REPORT_MONTH" type="REPORT_MONTH" />
<xs:element name="REPORT_YEAR" type="REPORT_YEAR" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="fileInfo">
<xs:sequence>
<xs:element name="PROCESS_DT" type="PROCESS_DT" />
<xs:element name="BATCH_NO" type="BATCH_NO" />
<xs:element name="COUNTY_CD" type="COUNTY_CD" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="mtrs_data">
<xs:sequence>
<xs:element name="SECTION" type="SECTION" />
<xs:element name="TOWNSHIP" type="TOWNSHIP" />
<xs:element name="TSHIP_DIR" type="TSHIP_DIR" />
<xs:element name="RANGE" type="RANGE" />
<xs:element name="RANGE_DIR" type="RANGE_DIR" />
<xs:element name="BASE_LN_MER" type="BASE_LN_MER" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ag_application_data">
<xs:complexContent>
<xs:extension base="application_data_abs">
<xs:sequence>
<xs:element name="AER_GND_IND" type="AER_GND_IND" />
<xs:element name="SITE_LOC_ID" type="SITE_LOC_ID" />
<xs:element name="ACRE_PLANTED" type="ACRE_PLANTED" />
<xs:element name="UNIT_PLANTED" type="UNIT_PLANTED" />
<xs:element name="APPLIC_TM" type="APPLIC_TM" />
<xs:element name="FUME_CD" type="FUME_CD" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="nonag_application_data">
<xs:complexContent>
<xs:extension base="application_data_abs">
<xs:sequence>
<xs:element name="APPLIC_CNT" type="APPLIC_CNT" />
<xs:element name="LICENSE_NO" type="LICENSE_NO" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<!--- "Ag" -->
<!--
Type A:
Data that would appear on individual lines
in the old A type
(F file type, agricultural job report)
Type B:
Data that would appear on individual lines
in the old B type
(F file type, agricultural monthly production summary)
-->
<xs:complexType name="ag_application">
<xs:complexContent>
<xs:extension base="application_abs">
<xs:sequence>
<xs:element name="mtrs_data" type="mtrs_data" />
<xs:element name="application_data" type="ag_application_data" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<!--- "Non_Ag" -->
<!--
Data that would appear on individual lines
in the old C type
(C file type, non-agricultural monthly summary)
-->
<xs:complexType name="nonag_application">
<xs:complexContent>
<xs:extension base="application_abs">
<xs:sequence>
<xs:element name="application_data" type="nonag_application_data" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<!-- The individual lines of data that are transmitted. -->
<xs:complexType name="data_lines">
<xs:sequence>
<xs:element name="Non_Ag" type="nonag_application" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="Ag" type="ag_application" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<!-- !!!!!!!!! End Complex Types !!!!!!!!! -->
<xs:element name="pur">
<xs:complexType>
<xs:sequence>
<xs:element name="County" minOccurs="0" maxOccurs="1">
<!--
Tag for counties to put county-specific
data in (eg, their batch number, timestamp,
contact info, etc)
-->
</xs:element>
<!-- File: information specific to the file -->
<xs:element name="File" type="fileInfo" minOccurs="1" maxOccurs="1"/>
<!-- Data: lines of data transmitted -->
<xs:element name="Data" type="data_lines" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema> -
Using java to fill in the blanks in an xml document via a schema
Hi all
What im trying to do is basically take an xml document and run it through a xml schema validator and then if the xsd has any default values to basically populate the original xml document with these default values
e.g.
<root>
<name>dave</name>
<name></name>
</root>
the schema would be something like
<xs:element name="name" default="bobby">
after schema validation i would want the document to be
<root>
<name>dave</name>
<name>bobby</name>
</root>
is that something possible to do in java with any specific xml frameworks out there? if so can any one give me any pointers in the right direction?i assume by the lack of response this cannot be done then :(
-
How to declare the namespace of XML document to use in oracle DB?
I have an XML Schema file( 'Hospital.xsd' ) that reference the XML document ('Hospitals.xml' ).
That I use JDeveloper to build them up.
JDeveloper had set the default namespace as 'http://www.example.org'
like this :
<?xml version="1.0" encoding="UTF-8" ?>
<Hospitals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org src/Hospital.xsd"
xmlns="http://www.example.org">
If I want these two files ('Hospital.xsd' and 'Hospitals.xml') placed into
the table in the oracle database.
1. Should I create two tables? one for XSD and another for XML.
2. Should I keep the XSD file in the oracle database?
3. What is the namespace to declare in the heading of XML file?
The database name or my website URL?
Thank you very much.
Kanokporn P.Sounds a lot like this question, only with less details.
how to read data from XML variable and insert into table variable
We can only help if you provide us details to help as we cannot see what you are doing and only know what you tell us. Plenty of examples abound on the forums that cover the topics you seek as well. -
XML document creation using reflection
Hi all,
I'm tyring to write a class which creates an XML document from objects passed in. For example, you call the add(Object) method and it takes your object, uses reflection, then outputs XML like this...
<fieldName>fieldValue<fieldName>
The only problem is that after looking through this forum I am a little concerned about the performance of my proposed solution (using reflection).
The class will be used in a batch process which processes millions of objects (to generate a whopping XML file that'll be sent on for further processing by a third party).
Is there a better way to do this than by using reflection?
This class is going to be used by multiple batch processes hence there will be lots of different object types passed (they'll also be new ones in the future that we don't even know about yet) hence my reflection choice.
Thanks,
ChrisThe only problem is that after looking through this
forum I am a little concerned about the performance of
my proposed solution (using reflection).The only way that you'll know for sure is if you try it out. Write the code, test it, then run it in a profiler to find out where the performance problems (if any) are.
Is there a better way to do this than by using
reflection?Probably not, if you want to pass any arbitrary object to it.
One possible alternative is to have "XML aware" objects: define an interface WritesXML, that defines a method toXML(). You then check to see whether the given object implements this interface, and if it does you simply call the method, otherwise you use reflection.
Another alternative, assuming that your objects follow the Bean pattern, is to create "XML-ifiers" on the fly, similar to the way an app-server handles JSPs. First time you see an object you create a class that will write it to XML, then compile this class and invoke it for all subsequent objects. This will require that you have a JDK installed on the runtime machine, that the objects follow the Bean pattern, and that the number of instances of a given class are very high.
This class is going to be used by multiple batch
processes hence there will be lots of different object
types passed (they'll also be new ones in the future
that we don't even know about yet) hence my reflection
choice.Sounds like a good reason to use reflection. -
Problem validating an XML document with a schema containing xs:include
I have a problem using an include statement in xsd. I try to include another
schema by using the include statement:
<xsd:include schemaLocation="../../XXX.xsd"/>
and get the xjc error:
s4s-att-invalid-value: Invalid attribute value for 'schemaLocation' in element 'include': cvc-datatype-valid.1.2.1.
Can anybody give me a hint what goes wrong here? THANKS!!!!
ayacheYour schemaLocation value is not a URI? To me, it looks like the value should conform to this:
http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/datatypes.html#anyURI
I will let you read all those specs to see whether that is your problem. -
Extracting data from an XML document that uses namespaces
Hello all,
Firstly, please let me wish you all a very happy and prosperous 2013!
I have a piece of XML containing namespaces (retrieved from a web service) and I am having difficulty extracting values
(If you're interested this is the webservice: http://api.worldbank.org/countries/FRA/indicators/NY.GDP.MKTP.CD?date=2009)
Here is some test code with two cases -
1) where I leave in the namespace and
2) where I strip out all references to the namespace
Case 1 doesn't work, whereas Case 2 works well.
I would prefer a more elegant solution than simply stripping out the namespace.
I have probably just misunderstood something about how to work with namespaces in PL/SQL.
Do any of you have suggestions about how best to approach this?
Many thanks in advance.
Niall.
set serveroutput on
set define off
DECLARE
v_xml XMLTYPE;
v_clob CLOB;
v_country VARCHAR2(255);
BEGIN
v_clob := '<?xml version="1.0" encoding="utf-8"?>
<wb:data page="1" pages="1" per_page="50" total="1" xmlns:wb="http://www.worldbank.org">
<wb:data>
<wb:indicator id="NY.GDP.MKTP.CD">GDP (current US$)</wb:indicator>
<wb:country id="FR">France</wb:country>
<wb:date>2009</wb:date>
<wb:value>2619685000757.11</wb:value>
<wb:decimal>0</wb:decimal>
</wb:data>
</wb:data>';
v_xml := XMLTYPE(v_clob);
SELECT extractvalue(v_xml,'/data/data[1]/country', 'xmlns:"http://www.worldbank.org/"')
INTO v_country
FROM dual;
dbms_output.put_line(' ');
dbms_output.put_line('*** Case 1');
dbms_output.put_line('*** '||nvl(v_country,'nothing'));
dbms_output.put_line(v_xml.getStringVal());
v_xml := XMLTYPE(replace(v_clob,'wb:')); -- strip out wb:
SELECT extractvalue(v_xml,'/data/data[1]/country', 'xmlns:"http://www.worldbank.org/"')
INTO v_country
FROM dual;
dbms_output.put_line(' ');
dbms_output.put_line('*** Case 2');
dbms_output.put_line('*** '||nvl(v_country,'nothing'));
dbms_output.put_line(v_xml.getStringVal());
END;
/Your case 1 query should be
(not tested)
SELECT extractvalue(v_xml,'/wb:data/wb:data[1]/wb:country', 'xmlns:wb="http://www.worldbank.org/"')If the XML is going to be small, you could also do it this way purely in PL/SQL
[url http://anononxml.blogspot.com/2010/06/xml-parsing-with-namespaces-via-plsql.html]XML Parsing with Namespaces via PL/SQL. Ignore the DOMDocument examples (first two) in there.
If the XML will be large and you are on 11.1 or greater, then it would be faster to insert the XML into a column in a DB table (could be a global temporary table) where the column is XMLType and the storage is SECUREFILE BINARY (default on 11.2.0.2+). Then you could use XMLTable, like
[url http://anononxml.blogspot.com/2010/08/xml-parsing-with-namespaces-via.html]XML Parsing with Namespaces via XMLTable -
Using "XML Document from XML Schema" in JDeveloper
Hi Experts,
I have a requirement to generate XML Document from XML Schema.
For this I have used "XML Document from XML Schema" feature in JDeveloper. It is found in File->New->General->XML Document form XML Schema.
I have registered a schema with jdev and got an XML document output for that successfully.
Now, I want to implement this feature in my code for generating XML documents when XSD files are provided.
Can any one please provide me with pointers to do that? I am sure there should be some libraries which can implement this feature.
Thanks,
DilbaghCreate an XML document from a Schema with the Oracle SchemaClassGenerator.
import oracle.xml.classgen.SchemaClassGenerator;
XMLSchema schema=new XMLSchema();
XSDBuilder builder = new XSDBuilder();
URL url = new URL(schemaUrl);
schema = (XMLSchema)builder.build(url);
SchemaClassGenerator generator = new SchemaClassGenerator();
Generate the Java classes from the example XML Schema.
generator.generate(schema);With the java classes construct an XML document. -
Validating xml document in java
Trying to do subject.
I'm trying to use xsd from file(schemasource = 1) and from clob (schemasource = 0). I have two xsd schemas common_types.xsd and migom.xsd. second includes first. The problem is that when I'm using common_types schema from file I get error
ORA-29532: Java call terminated by uncaught Java exception: oracle.xml.parser.v2.XMLParseException: An internal error condition occurred.
and when I validate xml against only first schema has being read from clob I get success, but when I add second xsd, i get the same error, which says nothing at all.
create or replace and compile java source named XmlTools AS
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import oracle.sql.CLOB;
import java.io.IOException;
import org.xml.sax.SAXException;
import java.sql.SQLException;
import java.lang.IllegalArgumentException;
import oracle.xml.parser.v2.XMLParseException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
public class XmlValidator
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public static void ValidateDocument(int schemasource, oracle.sql.CLOB schemadoc, oracle.sql.CLOB schemadoc1, oracle.sql.CLOB xmldoc) throws SAXException, IOException, SQLException, ParserConfigurationException, XMLParseException, IllegalArgumentException {
try
File myfile = new File(".//XML//common_types.xsd");
if (myfile.exists())
Serv.log("ValidateDocument", "file size" + Long.toString(myfile.length()));
/*else
Serv.log("ValidateDocument", "file doesn't exists" );
Serv.log("ValidateDocument", "1" );
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
Serv.log("ValidateDocument", "2" );
SAXParser saxParser = factory.newSAXParser();
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
if (schemasource == 0)
InputSource schemaIs = new InputSource(schemadoc.getCharacterStream());
InputSource schemaIs1 = new InputSource(schemadoc1.getCharacterStream());
InputSource[] schemas = {schemaIs, schemaIs1};
//saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemaIs);
saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemas);
else
saxParser.setProperty(JAXP_SCHEMA_SOURCE, ".//XML//common_types.xsd");
XMLReader reader = saxParser.getXMLReader();
//Получаем входной XML документ
InputSource documentIs = new InputSource(xmldoc.getCharacterStream());
Serv.log("ValidateDocument", "3" );
//Запуск разбора
reader.parse(documentIs);
Serv.log("ValidateDocument", "4" );
documentIs = null;
/*catch (SAXException e)
Serv.log("ValidateDocument", "SAXException" );
Serv.log("ValidateDocument", "document is not valid because ");
Serv.log("ValidateDocument", e.getMessage());
throw(e);
catch (ParserConfigurationException e)
Serv.log("ValidateDocument", "ParserConfigurationException" );
throw(e);
catch (IOException e)
Serv.log("ValidateDocument", "IOException" );
throw(e);
catch (XMLParseException e)
Serv.log("ValidateDocument", "XMLParseException" );
Serv.log("ValidateDocument", e.getMessage());
StackTraceElement[] stack = e.getStackTrace();
for (int i = 0; i < stack.length; i++)
Serv.log("stacktrace element no " + Integer.toString(i), "toString: " + stack.toString());
Serv.log("stacktrace element no " + Integer.toString(i), "file name: " + stack[i].getFileName() + ", class name: " + stack[i].getClassName() + ", method name: " + stack[i].getMethodName() + ", line : " + stack[i].getLineNumber());
throw(e);
catch (IllegalArgumentException e)
Serv.log("ValidateDocument", "IllegalArgumentException" );
Serv.log("ValidateDocument", e.getMessage());
throw(e);
additional information got from java stacktrace:
file name: XMLError.java, class name: oracle.xml.parser.v2.XMLError, method name: flushErrors1, line : 320 file name: NonValidatingParser.java, class name: oracle.xml.parser.v2.NonValidatingParser, method name: parseDocument, line : 300 file name: XMLParser.java, class name: oracle.xml.parser.v2.XMLParser, method name: parse, line : 200 file name: XMLTOOLS, class name: XmlValidator, method name: ValidateDocument, line : 86
my oracle version is Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod But my aim is to make it work on all versions starting from 9I found another examples of xml document validation in Java, but it seems to me that ORACLE's JVM doesn't include such class as SchemaFactory and class SAXParserFactory doesn't have method setSchema. Is it possible to update JVM installed in Oracle?
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource("contacts.xsd")}));
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource("document.xml")); -
Best class to use to cache an XML document
Hello all,
I have an utility class representing an XML document, used withing a web application. This document shall be cached in the session since within a request and during the sessions I read it often and to several other things like XPath and XSLT.
But I am having problems due to this Bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6322678
and keep bad file descriptor errors due to these stream "specialities". There is a standard way of using cached+precompiled XSL templates and I wonder if there is a similar things for XML documents.
So I need an internal variable in my class containing the raw XML document - so using streams is not an ideal solution in regards of the bug - i am getting "bad file descriptor" errors from time to time.
I am playing with the idea of storing the XML document within a simple String and create the required Class from it for the according operations like XPath evaluation and XSL transformation. But I think that is quite more resource hungry than reading the XML document from the filesystem each time...
Has anyone some hints on how to keep an XML document in memory internally?
Thanks and regards,
TimoRehi,
So, everything works really fine! Thanks. As promised, here some examples
with bad indentations etc...:
Doing XSL transformation:
import java.io.StringWriter;
import org.w3c.dom.Document;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
TransformerFactory tFac = TransformerFactory.newInstance();
Templates compiledXslt = tFac.newTemplates(sheet);
Transformer transformer = compiledXslt.newTransformer();
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(new DOMSource(this.doc), sr);
System.err.println(sw.toString());************************
Doing XPath was a surprise and was originally my problem (I called evaluate() with an InputStream that occassioannly failed), I tried also here with new DOMSource() what also failed although not being null or so... funny: evaluate() can directly be called w/ dom.Document:
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
(this.doc is a org.w3c.dom.Document)
public String getXPathEvaluationAsString(String expr) {
try {
XPath xp = XPathFactory.newInstance().newXPath();
return (String)xp.evaluate(
expr,
this.doc,
XPathConstants.STRING
} catch(Exception e) {
e.printStackTrace();
return " ";
}Thanks and regards,
Timo -
Loading/breaking large files containing multiple XML documents using plsql
Hi I have a requirement where in the client sends the multiple xml payloads/documents in a single text file. I need to load that into the xmltype varialbe. How to do this?
I'm able to load the entire document into a clob object, here.. all the xml payloads are loaded into a single row. When I try to access this I get a error
ORA-31001: Invalid resource handle or path name "/MobileInventoryResponse.dtd"
ORA-06512: at "SYS.XMLTYPE", line 254
ORA-06512: at line 1
This error is due to the dtd present in the xml document : <!DOCTYPE MobileInventoryResponse SYSTEM "MobileInventoryResponse.dtd">
But if I load the data into a clob after removing the doctype reference then I get the following error. Here to mulitple xml documents are loaded into a single clob row.
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00209: PI names starting with XML are reserved
Error at line 81
ORA-06512: at "SYS.XMLTYPE", line 254
ORA-06512: at line 1
When try to access this by using select xmltype(x) from t
where x is column type of clob.
Please let me know any method or type loading the multiple xml documents by using plsql. Only plsql method. There is a way by using SAX Loader. But can it be used in plsql or its a java method of loading.
Regards,
Naveen
Edited by: MAN on Oct 18, 2008 9:21 PMsorry for that...
There was enter character between some tags. From there I'm not receiving that particular error.
Now what I get is
ORA-31001: Invalid resource handle or path name "/MobileInventoryResponse.dtd"
ORA-06512: at "SYS.XMLTYPE", line 254
ORA-06512: at line 1
ORA-06512: at line 39
This is because there is a doctype at the start of the xml payload.
But if there is no <!DOCTYPE MobileInventoryResponse SYSTEM "MobileInventoryResponse.dtd"> this statement then it works fine.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MobileInventoryResponse SYSTEM "MobileInventoryResponse.dtd">
<MobileInventoryResponse>
And this exercise I'm doing in my Windows xp loaded operating system with a local instance of oracle ... Do i need to do any other setting.
Along with that I followed your method mentioned @ Re: LPX-00209: PI names starting with XML are reserved
ignore:=dbms_xdb.createResource('/MobileInventoryResponse.dtd',bfilename('XML_DIR','MobileInventoryResponse.dtd'));
And I'm not getting how it will refer the this resource.
this above partilcular statement . should it be executed when ever we insert into the table ? But in the dtd there is no word saying "MobileInventoryResponse".
got this error.
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00104: Warning: element "MobileInventoryResponse" is not declared in the DTD
Error at line 1
ORA-06512: at "SYS.XMLTYPE", line 254
ORA-06512: at line 1
ORA-06512: at line 21
This is how I'm doing in the block
DECLARE
l_filehandle UTL_FILE.FILE_TYPE;
l_filename VARCHAR2(50):='test.xml';
l_rec_data VARCHAR2(500);
l_rec_trim_data VARCHAR2(500);
l_rec_trim_upper VARCHAR2(500);
l_rec_full_data CLOB;
ignore boolean;
BEGIN
l_filehandle := UTL_FILE.FOPEN('XML_DIR',l_filename,'R');
--dbms_xdb.deleteResource('/MobileInventoryResponse.dtd',dbms_xdb.DELETE_RESOURCE );
LOOP
ignore:=dbms_xdb.createResource('/MobileInventoryResponse.dtd',bfilename('XML_DIR','MobileInventoryResponse.dtd'));
commit;
UTL_FILE.GET_LINE(l_filehandle, l_rec_data);
--dbms_output.put_line('l_rec_data : '|| l_rec_data);
-- Trim the record to remove spaces
l_rec_trim_data := TRIM(l_rec_data);
l_rec_trim_upper := UPPER(l_rec_trim_data);
l_rec_full_data := l_rec_full_data||l_rec_data;
IF l_rec_trim_upper LIKE '</MOBILEINVENTORYRESPONSE>' THEN
dbms_output.put_line('l_rec_full_data : '||l_rec_full_data);
INSERT INTO library_xml VALUES(xmltype(l_rec_full_data));
l_rec_full_data:=NULL;
END IF;
dbms_xdb.deleteResource('/MobileInventoryResponse.dtd',dbms_xdb.DELETE_RESOURCE );
commit;
END LOOP;
UTL_FILE.FCLOSE(l_filehandle);
COMMIT;
--exception just for testing purpose
EXCEPTION
WHEN no_data_found THEN
NULL;
commit;
END;
Edited by: MAN on Oct 21, 2008 2:47 AM -
Checking wellformedness of XML document
Hello,
Can anybody tell me how to check the well-formedness of an XML document in JAVA.
ThanksHi,
Being "well formed" just means matching start and end tags.
As far as I know.... all XML parsers check for that.
If you mean, valid, ie. checking an XML document against a DTD or XML Schema, then here's some source code I had lying around on my machine. Must've downloaded it from somewhere.
It compiles and runs.
regards,
Owen
// JAXP packages
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
import java.io.*;
public class TestSax extends DefaultHandler
/** Constants used for JAXP 1.2 */
static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
/** A Hashtable with tag names as keys and Integers as values */
private Hashtable tags;
// Parser calls this once at the beginning of a document
public void startDocument() throws SAXException
tags = new Hashtable();
// Parser calls this for each element in a document
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException
String key = localName;
Object value = tags.get(key);
if (value == null)
// Add a new entry
tags.put(key, new Integer(1));
else
// Get the current count and increment it
int count = ((Integer)value).intValue();
count++;
tags.put(key, new Integer(count));
// Parser calls this once after parsing a document
public void endDocument() throws SAXException
Enumeration e = tags.keys();
while (e.hasMoreElements())
String tag = (String)e.nextElement();
int count = ((Integer)tags.get(tag)).intValue();
System.out.println("Local Name \"" + tag + "\" occurs " + count + " times");
* Convert from a filename to a file URL.
private static String convertToFileURL(String filename)
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File(filename).getAbsolutePath();
if (File.separatorChar != '/')
path = path.replace(File.separatorChar, '/');
if (!path.startsWith("/"))
path = "/" + path;
return "file:" + path;
private static void usage()
System.err.println("Usage: TestXML [-options] <file.xml>");
System.err.println(" -dtd = DTD validation");
System.err.println(" -xsd | -xsdss <file.xsd> = W3C XML Schema validation using xsi: hints");
System.err.println(" in instance document or schema source <file.xsd>");
System.err.println(" -xsdss <file> = W3C XML Schema validation using schema source <file>");
System.err.println(" -usage or -help = this message");
System.exit(1);
public static void main (String[] args) throws Exception
String filename = null;
boolean dtdValidate = false;
boolean xsdValidate = false;
String schemaSource = null;
// Parse arguments
for (int i = 0; i < args.length; i++)
if (args.equals("-dtd"))
dtdValidate = true;
else if (args[i].equals("-xsd"))
xsdValidate = true;
else if (args[i].equals("-xsdss"))
if (i == args.length - 1)
usage();
xsdValidate = true;
schemaSource = args[++i];
else if (args[i].equals("-usage"))
usage();
else if (args[i].equals("-help"))
usage();
else
filename = args[i];
// Must be last arg
if (i != args.length - 1)
usage();
if (filename == null)
usage();
// There are several ways to parse a document using SAX and JAXP.
// We show one approach here. The first step is to bootstrap a
// parser. There are two ways: one is to use only the SAX API, the
// other is to use the JAXP utility classes in the
// javax.xml.parsers package. We use the second approach here
// because at the time of this writing it probably is the most
// portable solution for a JAXP compatible parser. After
// bootstrapping a parser/XMLReader, there are several ways to
// begin a parse. In this example, we use the SAX API.
// Create a JAXP SAXParserFactory and configure it
SAXParserFactory spf = SAXParserFactory.newInstance();
// Set namespaceAware to true to get a parser that corresponds to
// the default SAX2 namespace feature setting. This is necessary
// because the default value from JAXP 1.0 was defined to be false.
spf.setNamespaceAware(true);
// Validation part 1: set whether validation is on
spf.setValidating(dtdValidate || xsdValidate);
// Create a JAXP SAXParser
SAXParser saxParser = spf.newSAXParser();
// Validation part 2a: set the schema language if necessary
if (xsdValidate)
try
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
catch (SAXNotRecognizedException x)
// This can happen if the parser does not support JAXP 1.2
System.err.println( "Error: JAXP SAXParser property not recognized: "
+ JAXP_SCHEMA_LANGUAGE);
System.err.println("Check to see if parser conforms to JAXP 1.2 spec.");
System.exit(1);
// Validation part 2b: Set the schema source, if any. See the JAXP
// 1.2 maintenance update specification for more complex usages of
// this feature.
if (schemaSource != null)
saxParser.setProperty(JAXP_SCHEMA_SOURCE, new File(schemaSource));
// Get the encapsulated SAX XMLReader
XMLReader xmlReader = saxParser.getXMLReader();
// Set the ContentHandler of the XMLReader
xmlReader.setContentHandler(new TestSax());
// Set an ErrorHandler before parsing
xmlReader.setErrorHandler(new MyErrorHandler(System.err));
// Tell the XMLReader to parse the XML document
xmlReader.parse(convertToFileURL(filename));
// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler
/** Error handler output goes here */
private PrintStream out;
MyErrorHandler(PrintStream out)
this.out = out;
* Returns a string describing parse exception details
private String getParseExceptionInfo(SAXParseException spe)
String systemId = spe.getSystemId();
if (systemId == null)
systemId = "null";
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException
out.println("Warning: " + getParseExceptionInfo(spe));
public void error(SAXParseException spe) throws SAXException
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public void fatalError(SAXParseException spe) throws SAXException
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message); -
No default attributes while Parsing XML document
Hellow.
I have such a problem:
I have XML document that uses XSD-schema.
In XSD-schema there is element that have two atributes:
<xsd:complexType name = "El1">
<xsd:attribute name = "atr1" xsd:default = "0" type = "xsd:boolean"/>
<xsd:attribute name = "atr2" default = "0" type = "xsd:boolean"/>
</xsd:complexType>And in XML document I write:
<El1 atr1 = "1"/>According to the XSD-schema parser must add to El1 second attribute "atr2" with its default value because it has default value. But when I do such a code:
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.parse(new File("file1.xml"));
Element pEl;
pEl = doc.getDocumentElement()
NamedNodeMap Attribs = pEl.getAttributes();In the list of attributes "Attribs" - there is no attribute "attr1"!!!
What I have to do???Hello All
I am new to this parsing world. I have a doubt. I have an XML like
<xml>
<platform name = "windows">
<computer>
<hostname> hostname1 </hostname>
<IPAddress>127.0.3.03 </IPAddress>
</computer>
<computer>
<hostname> hostname2 </hostname>
<IPAddress>127.0.3.04 </IPAddress>
</computer>
</platform>
<platform name = "unix">
<computer>
<hostname> hostname6 </hostname>
<IPAddress>127.0.3.08 </IPAddress>
</computer>
<computer>
<hostname> hostname7 </hostname>
<IPAddress>127.0.3.09 </IPAddress>
</computer>
</platform>
</xml>
If i want to get details about individual computer under each platform as a string how do i do that?
Which parser would be ideal to be used DOM or SAX. -
JText Field with XML Document as a model
Hi All,
I have a swing application, which contains a number of JTextFields inside a form. These textfield represent certain elements of a XML document. The size and other constraints of these elements are specified in a schema. At the bottom, there is a save button which will save the form.
Can someone help me, in binding these textfields with the xml document, so that when I am typing in the textfields, the elements in the xml document gets updated. In other words, I want to set the XML document as the model for the textfields. Hence, when I click on the save button, at the bottom of the form, I will simply validate the XML document against the schema, and notify the user if there is any error in data entry.
Thanks a lot in advance,
~Debopamsorry for bumping it....but can someone help?
Maybe you are looking for
-
Your computer restarted because of a problem - macbook pro 2010
Hello Everybody, I been having a small issue with my 2010 macbook pro The problem is i was using my macbook when suddenly it just restarted and displayed the message " your computer restarted because of a problem " not sure why this happened. After t
-
Can anyone pls explain this part of the code. DateFormat dateFormat = new SimpleDateFormat ("MM/dd/yyyy"); Date birthDate = dateFormat.parse (birthDateString); Calendar day = Calendar.getInstance(); day.setTime (birthDate); int day = day.get (Calen
-
Dear Sir It is kindly requested to help us with these issue- we are not able to install the operating system(Microsoft server -2008 SP-2 (x 32 bit) Following error is coming during installation :- Windows server could not install due to one or more c
-
New ipod nano how to sync with previous itunes
My old ipod nano was recently broken and I just got a new one. I am not good with computers and have no idea how to get my computer and itunes to recognize the new ipod. Please help!!!!!!!
-
Good Receipt basedOutbound delivery
hi all what is Goods receipt based outbound delivery in transaction code MIGO or Goods receipt according outbound delivery? best ragards