Help: How to Validate XML using SAXParser and return the entire error list
Hi,
I have a problem, I'm trying to validate a xml document against the DTD. Here Im using SAXParser and having the ErrorHandler object passed when setting the error Handler, like parser.setErrorHandler(errorHandlerObj).
I need an output like where the entire XML document is read and all the errors have to be reported with the line number.
like example:
<b>Line 6: <promp>
[Error]:Element type "promp" must be declared.
Line 8: </prompt>
[Fatal Error]:The end-tag for element type "promp" must end with a '>' delimiter.
who can i achieve this.</b>
what happens with the present code is that it throws the first error it encountered and comes out.
how can i solve this problem
You can try to set the following feature to 'true' for your SAXParser:
http://apache.org/xml/features/continue-after-fatal-error
At least Xerces supports this feature.
Similar Messages
-
How to validate XML at runtime and show the exact cause of validation failure .
Hi
How can I validate my generated XML at runtine against its schema ? I have used
the validate() method and it does validate correctly against the schema but the
problem is it just returns a boolean . I need to know the exact cause of failure
(like for example The element X was supposed to contain Y,Z etc ). I need to capture
the exact exception (like a Sax Parse exception details).
How do i do that using XMLBeans ??
- BanaHi Bana,
You could use the XmlOptions.setErrorListener(Collection) method to get the detailed error message by invoking validate(option).
Kind Regards,
Jennifer -
How to validate XML against XSD and parse/save in one step using SAXParser?
How to validate XML against XSD and parse/save in one step using SAXParser?
I currently have an XML file and XSD. The XML file specifies the location of the XSD. In Java code I create a SAXParser with parameters indicating that it needs to validate the XML. However, SAXParser.parse does not validate the XML, but it does call my handler functions which save the elements/attributes in memory as it is read. On the other hand, XMLReader.parse does validate the XML against the XSD, but does not save the document in memory.
My code can call XMLReader.parse to validate the XML followed by SAXParser.parse to save the XML document in memory. But this sound inefficient. Besides, while a valid document is being parsed by XMLReader, it can be changed to be invalid and saved, and XMLReader.parse would be looking at the original file and would think that the file is OK, and then SAXParser.parse would parse the document without errors.
<Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="book.xsd" name="MyBook">
<Chapter name="First Chapter"/>
<Chapter name="Second Chapter">
<Section number="1"/>
<Section number="2"/>
</Chapter>
</Book>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Book">
<xs:complexType>
<xs:sequence>
<xs:element name="Chapter" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Section" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="xnumber"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name"/>
</xs:complexType>
</xs:element>
</xs:schema>
public class SAXXMLParserTest
public static void main(String[] args)
try
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
BookHandler handler = new BookHandler();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(handler);
parser.parse("xmltest.dat", handler); // does not throw validation error
Book book = handler.getBook();
System.out.println(book);
reader.parse("xmltest.dat"); // throws validation error because of 'xnumber' in the XSD
public class Book extends Element
private String name;
private List<Chapter> chapters = new ArrayList<Chapter>();
public Book(String name)
this.name = name;
public void addChapter(Chapter chapter)
chapters.add(chapter);
public String toString()
StringBuilder builder = new StringBuilder();
builder.append("<Book name=\"").append(name).append("\">\n");
for (Chapter chapter: chapters)
builder.append(chapter.toString());
builder.append("</Book>\n");
return builder.toString();
public static class BookHandler extends DefaultHandler
private Stack<Element> root = null;
private Book book = null;
public void startDocument()
root = new Stack<Element>();
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
if (qName.equals("Book"))
String name = attributes.getValue("name");
root.push(new Book(name));
else if (qName.equals("Chapter"))
String name = attributes.getValue("name");
Chapter child = new Chapter(name);
((Book)root.peek()).addChapter(child);
root.push(child);
else if (qName.equals("Section"))
Integer number = Integer.parseInt(attributes.getValue("number"));
Section child = new Section(number);
((Chapter)root.peek()).addSection(child);
root.push(child);
public void endElement(String uri, String localName, String qName) throws SAXException
Element finished = root.pop();
if (root.size() == 0)
book = (Book) finished;
public Book getBook()
return book;
public void error(SAXParseException e)
System.out.println(e.getMessage());
public void fatalError(SAXParseException e)
error(e);
public void warning(SAXParseException e)
error(e);
public class Chapter extends Element
public static class Section extends Element
private Integer number;
public Section(Integer number)
this.number = number;
public String toString()
StringBuilder builder = new StringBuilder();
builder.append("<Section number=\"").append(number).append("\"/>\n");
return builder.toString();
private String name;
private List<Section> sections = null;
public Chapter(String name)
this.name = name;
public void addSection(Section section)
if (sections == null)
sections = new ArrayList<Section>();
sections.add(section);
public String toString()
StringBuilder builder = new StringBuilder();
builder.append("<Chapter name=\"").append(name).append("\">\n");
if (sections != null)
for (Section section: sections)
builder.append(section.toString());
builder.append("</Chapter>\n");
return builder.toString();
}Edited by: sn72 on Oct 28, 2008 1:16 PMHave you looked at the XML DB FAQ thread (second post) in this forum? It has some examples for validating XML against schemas.
-
Hi All
please tell me how to validate xml using xsd
regardsTry using this link:
= http://www.google.nl/search?q=XML+validate+oracle for instance or
= use the search button on this forum and / or
= read the FAQ on this (XML DB FAQ
Thanks Eddie et all, for educating me via http://awads.net/wp/2006/11/14/barts-punishment-for-asking-dumb-questions (don't mind the URL , the info there is really useful)
The following link on this site is just brilliant: http://www.albinoblacksheep.com/flash/posting.php
Grz
Marco
Message was edited by:
mgralike -
How to validate XML using java_xml_pack-summer-02?
In jaxp1.1, we validate the xml file in this way:
c:\java -jar Validator.jar myBookStore.xml
However, in java_xml_pack-summer-02, which is latest version of jaxp, the Validator.jar is not available. So, how to validate xml file?
Pls help.develop your own validator... here is a quick and dirty one, which spits exceptions when error are met:
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class Validator
public static void main(String[] args) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
sp.parse(new File(args[0]), new DefaultHandler());
} -
Need help - How to Validate XML
I have just started playing around with XML in Flex2 and
can't figure out a few things. I have the following XML
var myData:XML =
<SPECIAL>
<ROW>
<ITEM_001 ITEM_NAME="TOLERANCE">10</ITEM_001>
<ITEM_002 ITEM_NAME="DIA A">.25</ITEM_002>
<ITEM_003 ITEM_NAME="DIA B">.5</ITEM_003>
</ROW>
<ROW>
<ITEM_001 ITEM_NAME="TOLERANCE">150</ITEM_001>
<ITEM_002 ITEM_NAME="DIA A">.25</ITEM_002>
<ITEM_003 ITEM_NAME="DIA B">.73</ITEM_003>
</ROW>
</_SPECIAL>
I want the extract the element name ITEM_00x from with the
row to use as a string in another portion of the app. For example,
I can get to the ITEM_NAME attribute (TOLERANCE) and to the value
(like 10). I can't figure out how to extract ITEM_001 short of
creating an XMLString and parsing it out. I'm sure there must be a
function or some other simple way to get it but I don't know what
it is.
Another thing I'd like to do is validate the xml somehow so I
can insure that I have a good format. Not sure how to do this in
Flex2. I'm uploading XML via HTTPService (e4X format) from users.
The only caveat is that the number of elements in each row can vary
depending on whom I get the xml from. I may have ITEM_001 thru
ITEM_010 in each row the first time and ITEM_001 thru ITEM_005 the
next.
Any help would be appreciated!
Warren KochThat didn't do it -- it just extracted "TOLERANCE", not
"ITEM_001". What I'm trying to do is create an array of objects
based on the XML. Here is the code:
public function CreateSpecialDataArray():Array {
var Data_Name:String;
var theData:Array = new Array();
var DataObject:Object;
for each (var propRow:XML in myData.SPECIAL.ROW) {
DataObject = new Object();
for each (var propItem:XML in propRow.*) {
Data_Name = propItem.@ITEM_NAME;
DataObject[Data_Name]=propItem.toString();
theData.push(DataObject);
It's making the DataObject with properties of TOLERANCE, etc.
I want to make the DataObject with properties of ITEM_001,
ITEM_002, etc. I can't use the @ITEM_NAME to do this. -
Query on sorting XML using XSLT and getting the same XML as output !
Hi,
Looking for one information regarding sorting XML using XSLT , with the sorted XML as output. For eg. my XML is :
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sort1.xsl"?>
<levelone>
<child ID="1" sort="5">
<name>Paul</name>
</child>
<child ID="2" sort="1">
<name>Adam</name>
</child>
<child ID="3" sort="2">
<name>Will</name>
</child>
</levelone>
and XSL :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/levelone">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="@sort"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="child">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
This does the sort based on Name. But I want to get the same xml as output with the name sorted. Eg.
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sort1.xsl"?>
<levelone>
<child ID="2" sort="1">
<name>Adam</name>
</child>
<child ID="1" sort="5">
<name>Paul</name>
</child>
<child ID="3" sort="2">
<name>Will</name>
</child>
</levelone>
Any pointers will be highly appreciated.
- ThanksDon't you want <xsl:sort select="name"/> rather than <xsl:sort select="@sort"/>?
-
How can I close ALL tabs and clear the entire history?
Since an update, I can no longer clear all my history... I cannot close a remaining tab. As much as thios has been my favorite browser, I am annoyed at the failure to protect privacy, and am considering deleting this entire program. Please give me a way to correct this and return to an earlier version.
To close the tab you're viewing, you can press Ctrl+w. Does that still leave an uncloseable tab? Is it a built-in page or a page on the web?
There are many methods to delete history in Firefox. Which is the one you're using to clear history? Is it one of these?
* Menu: History > Clear Recent History
* Library dialog (Ctrl+Shift+h): select entire list > right-click > Delete this page
In case you are having difficulties with regular vs. private browsing windows after the changes in Firefox 20, see whether this article helps: [[Private Browsing - Browse the web without saving information about the sites you visit]]. -
Help to search for a string value and return the index in the arraylist
Hello,
I just start java programming for the last three weeks and I cannot find a solution for this problem. I have the following List with string and integer value as shown below:
List<Empl> list= new ArrayList<Empl>();
list.add(new Empl(1,"Jim", "Balu",88);
list.add(new Empl(3,"Bob", "Howards",2);
list.add(new Empl(2,"Chris", "Hup",8);
I have no problem of sorting this arraylist either by firstname or lastname. However, I cannot think of a way to search for a firstname or lastname and returing the whole row. I do not want to use index since I am asking user to enter the name to search. Here is my code to search for an empl based on index.
System.out.print("Please enter index to search or (q)uit: ");
String ans = sc.next();
System.out.println();
int ians = Integer(ans);
if (ans.equalsIgnoreCase("q"))
choice = "n";
else
System.out.println("index " + list.get(ians)); //this will print out the whole row based on the index
Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?
Please advice and thank you.
Bob.user11191663 wrote:
Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?Another possibility is to set up an ArrayList for each thing you want to search on and then every time you add an employee, add the piece of data you want as well, viz:
Empl e = new Empl(1,"Jim", "Balu",88);
list.add(e);
firstNames.add(e.firstName());As long as you always add them in the same order, the indexes will match, so you could do something like
ians = firstNames.indexOf(nameToFind);to return the index of the name, if it's there (if not, it will return -1).
I wouldn't recommend this as standard practise, but it should be OK for the level you're at.
NOTE: indexOf() returns the index of the FIRST matching item. You may want to think about what you want to do if there are more than 1.
Winston -
How to filter xml using dtd and create a new xml document
Good morning my name is Antonio and I'm an italian programmer.
I need an help about the follow question.
I want to filter the contents of a XML document using a DTD to allow
only the valid elements and attributes as specified in the DTD to be
passed through to the output, any data that does not conform to the DTD
should be filtered out.
To resolve this problem there's XML Translator Generator (XTransGen): http://www.alphaworks.ibm.com/tech/xmltranslatorgenerator
but at moment it's not avaiable.
Can you help me?
Many thanks.
ciao
Antonio...
-
How to Parse XML with SAX and Retrieving the Information?
Hiya!
I have written this code in one of my classes:
/**Parse XML File**/
SAXParserFactory factory = SAXParserFactory.newInstance();
GameContentHandler gameCH = new GameContentHandler();
try
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(recentFiles[0], gameCH);
catch(javax.xml.parsers.ParserConfigurationException e)
e.printStackTrace();
catch(java.io.IOException e)
e.printStackTrace();
catch(org.xml.sax.SAXException e)
e.printStackTrace();
/**Parse XML File**/
games = gameCH.getGames();And here is the content handler:
import java.util.ArrayList;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
class GameContentHandler extends DefaultHandler
private ArrayList<Game> games = new ArrayList<Game>();
public void startDocument()
System.out.println("Start document.");
public void endDocument()
System.out.println("End document.");
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
public void characters(char[] ch, int start, int length) throws SAXException
/**for (int i = start; i < start+length; i++)
System.out.print(ch);
public ArrayList<Game> getGames()
return games;
}And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Database>
<Name></Name>
<Description></Description>
<CurrentGameID></CurrentGameID>
<Game>
<gameID></gameID>
<name></name>
<publisher></publisher>
<platform></platform>
<type></type>
<subtype></subtype>
<genre></genre>
<serial></serial>
<prodReg></prodReg>
<expantionFor></expantionFor>
<relYear></relYear>
<expantion></expantion>
<picPath></picPath>
<notes></notes>
<discType></discType>
<owner></owner>
<location></location>
<borrower></borrower>
<numDiscs></numDiscs>
<discSize></discSize>
<locFrom></locFrom>
<locTo></locTo>
<onLoan></onLoan>
<borrowed></borrowed>
<manual></manual>
<update></update>
<mods></mods>
<guide></guide>
<walkthrough></walkthrough>
<cheats></cheats>
<savegame></savegame>
<completed></completed>
</Game>
</Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
Please help someone...OK, how's this?
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
current = "";
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
try
if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
{return;}
else if(qualifiedName.equals("gameID"))
{games.add(new Game(Integer.parseInt(current)));}
else if(qualifiedName.equals("name"))
{games.get(games.size()-1).name = current;}
else if(qualifiedName.equals("publisher"))
{games.get(games.size()-1).publisher = current;}
etc...
else
{System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
catch (Exception e) {} //Ignore
public void characters(char[] ch, int start, int length) throws SAXException
current += new String(ch, start, length);
} -
How can I play a playlist and not the entire library on my shuffle?
I can't seem to organize songs into playlists and then play only the songs in the playlist -
There is if you play music from your computer (mine is connected via AirTunes to several stereo systems) or if you later get a Nano, or iPod with Video or an iPhone that does support playlists.
You can also use them to load songs on your Shuffle. For example, say you are going on a long exercise walk and you want many motivational songs with increasingly faster tempos. You could create a playlist on your computer, put the songs in it that you want, in the order you want, call it Long Walk, and then when your Shuffle is connected choose to Autofill from the playlist Long Walk -
How to get UTF-8 encoding when create XML using DBMS_XMLGEN and UTL_FILE ?
How to get UTF-8 encoding when create XML using DBMS_XMLGEN and UTL_FILE ?
Hi,
I do generate XML-Files by using DBMS_XMLGEN with output by UTL_FILE
but it seems, the xml-Datafile I get on end is not really UTF-8 encoding
( f.ex. cannot verifying it correct in xmlspy )
my dbms is
NLS_CHARACTERSET = WE8MSWIN1252
NLS_NCHAR_CHARACTERSET = AL16UTF16
NLS_RDBMS_VERSION = 10.2.0.1.0
I do generate it in this matter :
declare
xmldoc CLOB;
ctx number ;
utl_file.file_type;
begin
-- generate fom xml-view :
ctx := DBMS_XMLGEN.newContext('select xml from xml_View');
DBMS_XMLGEN.setRowSetTag(ctx, null);
DBMS_XMLGEN.setRowTag(ctx, null );
DBMS_XMLGEN.SETCONVERTSPECIALCHARS(ctx,TRUE);
-- create xml-file:
xmldoc := DBMS_XMLGEN.getXML(ctx);
-- put data to host-file:
vblob_len := DBMS_LOB.getlength(xmldoc);
DBMS_LOB.READ (xmldoc, vblob_len, 1, vBuffer);
bHandle := utl_file.fopen(vPATH,vFileName,'W',32767);
UTL_FILE.put_line(bHandle, vbuffer, FALSE);
UTL_FILE.fclose(bHandle);
end ;
maybe while work UTL_FILE there is a change the encoding ?
How can this solved ?
Thank you
Norbert
Edited by: astramare on Feb 11, 2009 12:39 PM with database charsetsMarco,
I tryed to work with dbms_xslprocessor.clob2file,
that works good,
but what is in this matter with encoding UTF-8 ?
in my understandig, the xmltyp created should be UTF8 (16),
but when open the xml-file in xmlSpy as UTF-8,
it is not well ( german caracter like Ä, Ö .. ):
my dbms is
NLS_CHARACTERSET = WE8MSWIN1252
NLS_NCHAR_CHARACTERSET = AL16UTF16
NLS_RDBMS_VERSION = 10.2.0.1.0
-- test:
create table nh_test ( s0 number, s1 varchar2(20) ) ;
insert into nh_test (select 1,'hallo' from dual );
insert into nh_test (select 2,'straße' from dual );
insert into nh_test (select 3,'mäckie' from dual );
insert into nh_test (select 4,'euro_€' from dual );
commit;
select * from nh_test ;
S0 S1
1 hallo
1 hallo
2 straße
3 mäckie
4 euro_€
declare
rc sys_refcursor;
begin
open rc FOR SELECT * FROM ( SELECT s0,s1 from nh_test );
dbms_xslprocessor.clob2file( xmltype( rc ).getclobval( ) , 'XML_EXPORT_DIR','my_xml_file.xml');
end;
( its the same when using output with DBMS_XMLDOM.WRITETOFILE )
open in xmlSpy is:
<?xml version="1.0"?>
<ROWSET>
<ROW>
<S0>1</S0>
<S1>hallo</S1>
</ROW>
<ROW>
<S0>2</S0>
<S1>straޥ</S1>
</ROW>
<ROW>
<S0>3</S0>
<S1>m㢫ie</S1>
</ROW>
<ROW>
<S0>4</S0>
<S1>euro_</S1>
</ROW>
</ROWSET>
regards
Norbert -
Query resultset to xml using java and XML schema
Hi,
I query data using JDBC and I want to store it to an XML file which has a well defined XML schema. I searched a lot in the forum but did not find an answer. Please guide me to create this program.
I have managed to use JDBC to get result set but I do not know how to export is to XML using XSD and Java.
Please help.
Regards,
RaviI have managed to use JDBC to get result set but I do
not know how to export is to XML using XSD and Java.Export using XSD? Schemas are for validation.
Iterate through the result set, and build up the XML stream by creating an entry for each row.
Another way to do it is to load the ResultSet into a Java object and serialize that to XML using something like XStream.
% -
How can I download itunes when I get the following errors ..ituneshelper did not install correctly error 7..I .have installed and uninstalled a dozen times with various fixes...b noir for example and used Revo to clean up.
This has been a problem for 6 weeks now, I retry when I have time and patience and use my other laptop which is also Windows 7 and runs with no problem.
Every attempt fails when all seems fine on the desktop and I try to log on to Itunes I get the errors.
Any help greatly appreciated.
billymacGo to Control Panel > Add or Remove Programs (Win XP) or Programs and Features(Later)
Remove all of these items in the following order:
iTunes
Apple Software Update
Apple Mobile Device Support (If this won't uninstall press on)
Bonjour
Apple Application Support
Reboot, download iTunes, then reinstall, either using an account with administrative rights, or right-clicking the downloaded installer and selecting Run as Administrator.
See also HT1925: Removing and Reinstalling iTunes for Windows XP or HT1923: Removing and reinstalling iTunes for Windows Vista, Windows 7, or Windows 8
Should you get the error iTunes.exe - Entry Point Not Found after the above reinstall then copy QTMovieWin.dll from:
C:\Program Files (x86)\Common Files\Apple\Apple Application Support
and paste into:
C:\Program Files (x86)\iTunes
The above paths would be for a 64-bit machine. Hopefully the same fix with the " (x86)" omitted would work on 32-bit systems with the same error.
tt2
Maybe you are looking for
-
Creating a Double[][]
Hello, I am trying to make a Double[][] like so..... Double[][] size = {{200,200,200,200},{50,50,50,50,50,50,300}};I have done this before in other programs. however when i try it now i get this error..... mohadib@mohadib ~/java_restore/contacts_act-
-
Allocation of Profit Center actual postings
Hi all, Have a question regarding on how to allocate the actual postings done to a profit center. Are there any other methods aside from the assessment (3KE5) and distribution (4KE5). Also, i have found a sap note that allows the creation of cycles (
-
FaceTime HD camera not working at all?
Recently, I opened up photobooth and tried to use the built in camera on my 13 inch macbook air and while the green light on the camera was on, all that appeared on the screen of photobooth was the rotaingloading symbol. I got in april 2013, so it sh
-
Refine edge tool (CS5) producing bad quality selections?
I am having troubles where whenever I use the refine edge tool, the selection it produces is horrible quality. What's weird is on my old computer, running the same software and using the same images, I could get much better results. I was runnign Vi
-
Hi all we have a requirement that ,we r getting two rows in a page of irec when it is getting rendered,our requirement is to hide the one row from that table and delete that from database as well, while the page is getting rendered.We extended the CO