SAX / Validating XML file...
Hello,
I would like to use the SAX Parser to validate a XML file. So I've downloaded the last sax.jar library and included it in the java 1.4 directory.
If I set the setvalidating flag to false the parser is working great and i have good results. However I would like to validate the XML file with a XML Schema (that can be accessed using the web). So I saw the Sun tutorial for doing that but have a terrible error ! :
java.lang.ClassCastException
at org.apache.xerces.impl.xs.XMLSchemaValidator.reset(XMLSchemaValidator.java:1332)
and don't understand why, can somebody help me ????
public class AgentHandler
extends DefaultHandler
implements ContentHandler {
private boolean isAgent;
private boolean isAgentViaProxy;
private AgentTable agentTable;
private String agent;
private String proxy;
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";
private String representation;
private StringBuffer content = new StringBuffer();
MimeBodyPart part;
Unit currentUnit;
Consumer nextConsumer;
protected Object object;
public AgentTable getAgentTable() {
ErrorHandler errorHandler = new MyErrorHandler();
content.setLength(0);
agentTable = new AgentTable();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser saxParser = null;
try {
saxParser = factory.newSAXParser();
catch (ParserConfigurationException ex1) {
ex1.printStackTrace();
catch (SAXException ex1) {
ex1.printStackTrace();
try {
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
//agentfile.xml is the XML Schema
saxParser.setProperty(
"http://apache.org/xml/properties/schema/external-schemaLocation",
new File(
"http://localhost:8080/agentfile.xml"));
catch (SAXNotSupportedException ex3) {
ex3.printStackTrace();
catch (SAXNotRecognizedException ex3) {
ex3.printStackTrace();
org.xml.sax.XMLReader xmlReader = null;
try {
xmlReader = saxParser.getXMLReader();
catch (SAXException ex) {
ex.printStackTrace();
xmlReader.setContentHandler(this);
xmlReader.setErrorHandler(errorHandler);
try {
xmlReader.parse(new org.xml.sax.InputSource(jamap.share.Constants.homeDir +
jamap.share.Constants.
AgentFile));
catch (SAXException ex2) {
ex2.printStackTrace();
System.out.println("Error in parsing the agent.xml file");
catch (IOException ex2) {
ex2.printStackTrace();
System.out.println("Error in parsing the agent.xml file");
return agentTable;
}any idea ???
Thanks...
PA
Hello,
I did some modifications and now it is working : the setproperty was not properly called before....
Now I have an other problem : in fact the parser doesn't ignore the white spaces, even if I put an ignorableWhitespace method inside the handler : have you any idea to remove these new lines or spaces automatically during the parsing ????
TU...
PA
public AgentTable getAgentTable() {
ErrorHandler errorHandler = new MyErrorHandler();
content.setLength(0);
agentTable = new AgentTable();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser saxParser = null;
try {
saxParser = factory.newSAXParser();
catch (ParserConfigurationException ex1) {
ex1.printStackTrace();
catch (SAXException ex1) {
ex1.printStackTrace();
try {
saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
try {
saxParser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
new org.xml.sax.InputSource("http://localhost:8080/agentfile.xml")
catch (SAXNotRecognizedException ex4) {
catch (SAXNotSupportedException ex4) {
catch (SAXNotSupportedException ex3) {
ex3.printStackTrace();
catch (SAXNotRecognizedException ex3) {
ex3.printStackTrace();
org.xml.sax.XMLReader xmlReader = null;
try {
xmlReader = saxParser.getXMLReader();
catch (SAXException ex) {
ex.printStackTrace();
xmlReader.setContentHandler(this);
xmlReader.setErrorHandler(errorHandler);
try {
xmlReader.parse(new org.xml.sax.InputSource(jamap.share.Constants.homeDir +
jamap.share.Constants.
AgentFile));
catch (SAXException ex2) {
ex2.printStackTrace();
System.out.println("Error in parsing the agent.xml file");
catch (IOException ex2) {
ex2.printStackTrace();
System.out.println("Error in parsing the agent.xml file");
return agentTable;
Similar Messages
-
Error in validation.xml file while deploying in server
Hi friends,
I am Venkataramana . I am doing one small structs application with Validation . as usual in XML file i wrote validations but when i am deploying in server it is showing error as
SEVERE: Parse Error at line 2 column 17: Document is invalid: no grammar found.
org.xml.sax.SAXParseException: Document is invalid: no grammar found.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236)
and
Jan 11, 2010 11:57:53 PM org.apache.commons.digester.Digester error
SEVERE: Parse Error at line 2 column 17: Document root element "form-validation", must match DOCTYPE root "null".
org.xml.sax.SAXParseException: Document root element "form-validation", must match DOCTYPE root "null".
Kindly find the validation.xml file for your reference.
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<formset>
<form name="regFormForm">
<field property="username"
depends="required">
<arg0 key="uname"/>
</field>
<field property="password"
depends="required">
<arg0 key="password"/>
</field>
</form>
</formset>
</form-validation>
Please can any one help on this?I think your dtd entry - "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd" is not compatible with your validation.jar file. If you have recently downloaded the these struts jar files then make sure this entry is matched with what they have provided in examples. Or download new set of jar files and copy the same doc-type tag as they have given in examples.
-
XML Publisher question - Not generating a valid XML file
I am working through an Oracle document that walks you through creating an XML Pub report. I am using HCM 8.9, Tools 8.49.15 and it has XML Pub installed and I have the Microsoft plug-in installed
I have created a query and have downloaded an rtf template and now am on a page where you enter your data source and then click ‘Generate’ for the sample data file. I did it and it created ‘PERSONAL_DATA_PAY.XML’ which is created from a PS Query. However if I click on ‘PERSONAL_DATA_PAY.XML’ it generates a blocky text file that is not an XML file and I can’t go any further.
Do you know why it’s not generating a valid XML file when I click on 'generate'?
Thanks
Allen H. Cunningham
Data Base Administrator - Oracle/PeopleSoft
Sonoma State UniversityYou mean to say that you create a new data source by specifying Data Source Type as 'PS Query' and Data Source ID as your query name, you are not able to generate a valid XML file (by clicking on Generate link).
did you cross check your query by running it?
On field change of Generate link, PeopleSoft uses PSXP_RPTDEFNMANAGER and PSXP_XMLGEN app packagaes and query objects to create the file
It should work if you query is valid.. -
XML Publisher does not create a valid XML file when I try to 'generate '
I am working through an Oracle document that walks you through creating an XML Pub report. I am using HCM 8.9, Tools 8.49.15 and it has XML Pub installed and I have the Microsoft plug-in installed
I have created a query and have downloaded an rtf template and now am on a page where you enter your data source and then click ‘Generate’ for the sample data file. I did it and it created ‘PERSONAL_DATA_PAY.XML’ which is created from a PS Query. However if I click on ‘PERSONAL_DATA_PAY.XML’ it generates a blocky text file that is not an XML file and I can’t go any further.
Do you know why it’s not generating a valid XML file when I click on 'generate'?
Thanks
Allen H. Cunningham
Data Base Administrator - Oracle/PeopleSoft
Sonoma State UniversityOn the right click on HD under video quality to filter it.
-
Infopath 2013 SOAP Web Service Data Connection - Error: The file is not a valid XML file
Here are the steps to replicate the issue I’m having when adding lists.asmx or any other SharePoint web service in InfoPath 2013. This web service opens fine in the browser from my desktop. My account is a farm administrator and is added to the
web application’s User Policy. I can use these services just fine using Nintex 2013 Workflow.
Open InfoPath Designer 2013.
Select Blank Form and click Design Form button.
Click “Data” tab.
Click “From Web Service” and select “From SOAP Web Service”
Enter https://mysiteurl.com/_vti_bin/lists.asmx?WSDL for the web service definition.
Click Next.
Windows Security window pops up.
Enter a credential. I tried both my account and the farm account. My account is a farm admin and is added to the web application’s User Policy with Full Control.
Click OK. It prompts for credential multiple times.
I get below this error messages:
Sorry, we couldn't open https://mysiteurl.com/_vti_bin/lists.asmx?WSDL
InfoPath cannot find or cannot access the specified Web Service description.
The file is not a valid XML file.
Not enough storage is available to process this command.
We have a project that is in need of these services using InfoPath so any help is greatly appreciated.Hi Brian_TX,
For your issue, try to the following methods:
Change your service binding in web.config to:binding="basicHttpBinding". It seems in VS it defaults to wsHttpBinding.
Replace all instances of "parameters" from the web service wsdl with the name "parameter"
There are some similar articles about the issue, you can have a look at them:
http://www.infopathdev.com/forums/t/23239.aspx
https://social.msdn.microsoft.com/Forums/office/en-US/621929c3-0335-40af-8332-5a0b430901ab/problems-with-infopath-web-service-connection?forum=sharepointcustomizationprevious
https://social.msdn.microsoft.com/Forums/en-US/5fa5eca8-f8d7-4a2e-81ba-a3b4bdcfe5af/infopath-cannot-find-or-cannot-access-the-specified-web-service-description?forum=sharepointcustomizationlegacy
Best Regards
Lisa Chen
Forum Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected] -
Hi All,
We are trying to access the Create Deployment method stated below
http://msdn.microsoft.com/en-us/library/windowsazure/ee460813
We have uploaded the Package in the blob and browsing the configuration file. We have checked trying to upload manually the package and config file in Azure portal and its working
fine.
Below is the code we have written for creating deployment where "AzureEcoystemCloudService" is our cloud service name where we want to deploy our package. I have also highlighted the XML creation
part.
byte[] bytes =
new byte[fupldConfig.PostedFile.ContentLength + 1];
fupldConfig.PostedFile.InputStream.Read(bytes, 0, bytes.Length);
string a = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
string base64ConfigurationFile = a.ToBase64();
X509Certificate2 certificate =
CertificateUtility.GetStoreCertificate(ConfigurationManager.AppSettings["thumbprint"].ToString());
HostedService.CreateNewDeployment(certificate,
ConfigurationManager.AppSettings["SubscriptionId"].ToString(),
"2012-03-01", "AzureEcoystemCloudService", Infosys.AzureEcosystem.Entities.Enums.DeploymentSlot.staging,
"AzureEcoystemDeployment",
"http://shubhendustorage.blob.core.windows.net/shubhendustorage/Infosys.AzureEcoystem.Web.cspkg",
"AzureEcoystemDeployment", base64ConfigurationFile,
true, false);
<summary>
/// </summary>
/// <param name="certificate"></param>
/// <param name="subscriptionId"></param>
/// <param name="version"></param>
/// <param name="serviceName"></param>
/// <param name="deploymentSlot"></param>
/// <param name="name"></param>
/// <param name="packageUrl"></param>
/// <param name="label"></param>
/// <param name="base64Configuration"></param>
/// <param name="startDeployment"></param>
/// <param name="treatWarningsAsError"></param>
public static
void CreateNewDeployment(X509Certificate2 certificate,
string subscriptionId,
string version, string serviceName, Infosys.AzureEcosystem.Entities.Enums.DeploymentSlot deploymentSlot,
string name, string packageUrl,
string label, string base64Configuration,
bool startDeployment, bool treatWarningsAsError)
Uri uri = new
Uri(String.Format(Constants.CreateDeploymentUrlTemplate, subscriptionId, serviceName, deploymentSlot.ToString()));
XNamespace wa = Constants.xmlNamespace;
XDocument requestBody =
new XDocument();
String base64ConfigurationFile = base64Configuration;
String base64Label = label.ToBase64();
XElement xName = new
XElement(wa + "Name", name);
XElement xPackageUrl =
new XElement(wa +
"PackageUrl", packageUrl);
XElement xLabel = new
XElement(wa + "Label", base64Label);
XElement xConfiguration =
new XElement(wa +
"Configuration", base64ConfigurationFile);
XElement xStartDeployment =
new XElement(wa +
"StartDeployment", startDeployment.ToString().ToLower());
XElement xTreatWarningsAsError =
new XElement(wa +
"TreatWarningsAsError", treatWarningsAsError.ToString().ToLower());
XElement createDeployment =
new XElement(wa +
"CreateDeployment");
createDeployment.Add(xName);
createDeployment.Add(xPackageUrl);
createDeployment.Add(xLabel);
createDeployment.Add(xConfiguration);
createDeployment.Add(xStartDeployment);
createDeployment.Add(xTreatWarningsAsError);
requestBody.Add(createDeployment);
requestBody.Declaration =
new XDeclaration("1.0",
"UTF-8", "no");
XDocument responseBody;
RestApiUtility.InvokeRequest(
uri, Infosys.AzureEcosystem.Entities.Enums.RequestMethod.POST.ToString(),
HttpStatusCode.Accepted, requestBody, certificate, version,
out responseBody);
<summary>
/// A helper function to invoke a Service Management REST API operation.
/// Throws an ApplicationException on unexpected status code results.
/// </summary>
/// <param name="uri">The URI of the operation to invoke using a web request.</param>
/// <param name="method">The method of the web request, GET, PUT, POST, or DELETE.</param>
/// <param name="expectedCode">The expected status code.</param>
/// <param name="requestBody">The XML body to send with the web request. Use null to send no request body.</param>
/// <param name="responseBody">The XML body returned by the request, if any.</param>
/// <returns>The requestId returned by the operation.</returns>
public static
string InvokeRequest(
Uri uri,
string method,
HttpStatusCode expectedCode,
XDocument requestBody,
X509Certificate2 certificate,
string version,
out XDocument responseBody)
responseBody =
null;
string requestId = String.Empty;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
request.Headers.Add("x-ms-Version", version);
request.ClientCertificates.Add(certificate);
request.ContentType =
"application/xml";
if (requestBody != null)
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter streamWriter =
new StreamWriter(
requestStream, System.Text.UTF8Encoding.UTF8))
requestBody.Save(streamWriter,
SaveOptions.DisableFormatting);
HttpWebResponse response;
HttpStatusCode statusCode =
HttpStatusCode.Unused;
try
response = (HttpWebResponse)request.GetResponse();
catch (WebException ex)
// GetResponse throws a WebException for 4XX and 5XX status codes
response = (HttpWebResponse)ex.Response;
try
statusCode = response.StatusCode;
if (response.ContentLength > 0)
using (XmlReader reader =
XmlReader.Create(response.GetResponseStream()))
responseBody =
XDocument.Load(reader);
if (response.Headers !=
null)
requestId = response.Headers["x-ms-request-id"];
finally
response.Close();
if (!statusCode.Equals(expectedCode))
throw new
ApplicationException(string.Format(
"Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}",
uri.ToString(),
Environment.NewLine,
(int)statusCode,
statusCode,
responseBody.ToString(SaveOptions.OmitDuplicateNamespaces)));
return requestId;
But every time we are getting the below error from the line
response = (HttpWebResponse)request.GetResponse();
<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>BadRequest</Code>
<Message>The specified configuration settings for Settings are invalid. Verify that the service configuration file is a valid XML file, and that role instance counts are specified as positive integers.</Message>
</Error>
Any help is appreciated.
Thanks,
ShubhenduPlease find the request XML I have found it in debug mode
<CreateDeployment xmlns="http://schemas.microsoft.com/windowsazure">
<Name>742d0a5e-2a5d-4bd0-b4ac-dc9fa0d69610</Name>
<PackageUrl>http://shubhendustorage.blob.core.windows.net/shubhendustorage/WindowsAzure1.cspkg</PackageUrl>
<Label>QXp1cmVFY295c3RlbURlcGxveW1lbnQ=</Label>
<Configuration>77u/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0NCiAgKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KDQogIFRoaXMgZmlsZSB3YXMgZ2VuZXJhdGVkIGJ5IGEgdG9vbCBmcm9tIHRoZSBwcm9qZWN0IGZpbGU6IFNlcnZpY2VDb25maWd1cmF0aW9uLkNsb3VkLmNzY2ZnDQoNCiAgQ2hhbmdlcyB0byB0aGlzIGZpbGUgbWF5IGNhdXNlIGluY29ycmVjdCBiZWhhdmlvciBhbmQgd2lsbCBiZSBsb3N0IGlmIHRoZSBmaWxlIGlzIHJlZ2VuZXJhdGVkLg0KDQogICoqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioNCi0tPg0KPFNlcnZpY2VDb25maWd1cmF0aW9uIHNlcnZpY2VOYW1lPSJXaW5kb3dzQXp1cmUxIiB4bWxucz0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9TZXJ2aWNlSG9zdGluZy8yMDA4LzEwL1NlcnZpY2VDb25maWd1cmF0aW9uIiBvc0ZhbWlseT0iMSIgb3NWZXJzaW9uPSIqIiBzY2hlbWFWZXJzaW9uPSIyMDEyLTA1LjEuNyI+DQogIDxSb2xlIG5hbWU9IldlYlJvbGUxIj4NCiAgICA8SW5zdGFuY2VzIGNvdW50PSIyIiAvPg0KICAgIDxDb25maWd1cmF0aW9uU2V0dGluZ3M+DQogICAgICA8U2V0dGluZyBuYW1lPSJNaWNyb3NvZnQuV2luZG93c0F6dXJlLlBsdWdpbnMuRGlhZ25vc3RpY3MuQ29ubmVjdGlvblN0cmluZyIgdmFsdWU9IkRlZmF1bHRFbmRwb2ludHNQcm90b2NvbD1odHRwcztBY2NvdW50TmFtZT1zaHViaGVuZHVzdG9yYWdlO0FjY291bnRLZXk9WHIzZ3o2aUxFSkdMRHJBd1dTV3VIaUt3UklXbkFrYWo0MkFEcU5saGRKTTJwUnhnSzl4TWZEcTQ1ZHI3aDJXWUYvYUxObENnZ0FiZnhONWVBZ2lTWGc9PSIgLz4NCiAgICA8L0NvbmZpZ3VyYXRpb25TZXR0aW5ncz4NCiAgPC9Sb2xlPg0KPC9TZXJ2aWNlQ29uZmlndXJhdGlvbj4=</Configuration>
<StartDeployment>true</StartDeployment>
<TreatWarningsAsError>false</TreatWarningsAsError>
</CreateDeployment>
Shubhendu G -
How is the Login-validation.xml file is called when we do the validation i
Hi ^^,
please forgive me if I am a big long while explaining.
when you are using the struts 2.0 the web.xml has a welcome-file-list. I have put index.html in that list so it pulls up first.
It has the following tag
<ul>
<li><a href="roseindia/showLoginClientSideValidation.action">Login Application (Client Side Validation)</a></li>
</ul>so this maps to struts.xml which contains the showLoginClientSideValidation.action tag
<action name="showLoginClientSideValidation">
<result>/pages/loginClientSideValidation.jsp</result>
</action>
<action name="doLoginClientSideValidation" class="net.roseindia.Login">
<result name="input">/pages/loginClientSideValidation.jsp</result>
<result name="error">/pages/loginClientSideValidation.jsp</result>
<result>/pages/Loginsuccess.jsp</result>
</action>
this displays the jsp "loginClientSideValidation.jsp"
once you enter the details in the jsp and click submit the control goes to Login.java file as per the mapping in struts.xml given above
This is just a simple java file which contains the execute() method. This method returns success or error.
If success is returned then the Loginsuccess.jsp is invoked
If error is returned then the loginClientSideValidation.jsp is invoked
Well so far so good
I have also understood that to use client side validation you use validate = "true" in loginClientSideValidation.jsp
However what I am not able to understand is how the Login-validation.xml file is being invoked
Any help would be highly appreciated.
thanks and regards,Hi ^^^,
i found something interesting that I want to share
Validation rules are handled by validators, which must be registered with the ValidatorFactory (using the registerValidator method). The simplest way to do so is to add a file name validators.xml in the root of the classpath (/WEB-INF/classes) that declares all the validators you intend to use.
validators.xml if being defined should be available in the classpath. However this is not necessary, if no custom validator is needed. Webwork will automatically picked up a predefined sets of validators defined in com/opensymphony/xwork/validator/validators/default.xml packaged together in xwork jar file that comes with webwork distribution.
So this is clear that the validators are defined in validators.xml or default.xml
What is still not clear is how is the Login-validation.xml being called by jsp page to do verification and then linking to validators.xml to apply the rules.
However people have been telling me that ----" Struts 2.0 have inbuilt functionalities to validate the Parameters" and that i need to
"Define configuration file *-validation.xml or use annotations
i) className-validation.xml
ii) place this file in the directory where .class file is placed example.Login should have Login-validation.xml
Do you all think is this sufficient for an answer or should my search go on?
thanks and regards,
Prashant
Edited by: pksingh79 on Sep 13, 2008 10:08 AM -
Time validation from validation.xml file
i've inherited part of a project and need to be able to validate a user inputting time into a field, at present it's set for a 24 hr clock, but the mask as it is will let them input eg 25:45, because its checking each digit rather than is it less than 24
entry from our validation.xml file:
<field property="time" indexedListProperty="configBillingPeriodTable" depends="mask">
<arg0 key="taWebLabel.Time"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-2][0-9]:[0-5][0-9]$</var-value>
</var>
</field>
this stuff is new to me, so excuse the basic questions!! how can I set the first part of the mask to limit to 23, and where can I find info on what expressions I can use between the <var-value></var-value> tags
thnxI believe it would be this:
^([0-1][0-9]|[2][0-3]):[0-5][0-9]$
or if you don't want leading 0's for 0-9...
^([0-9]|[1][0-9]|[2][0-3]):[0-5][0-9]$ -
Fatal error XML-0121 in a valid XML file in v2 of SAX parser
Attachments: "1|type=text/plain|desc=Logging of Fatal error using v2 of SAX parser |file=v2_loggin
.txt|";"2|type=text/plain|desc=Logging of Fatal error using v2 of java SAX parser |17078|file=v2_l
gging.txt|"
Dear XML team,
I am using the SAX parser version 2.0.2.4. When parsing a valid
XML of approx. 3,5 Megabytes i get a fatal error XML-0121
saying 'End tag does not match start tag
<CORRESPONDENTIENAAM1>...'
We checked the xml on the well formedness with tools like XML
Spy and IE5. The XML is valid!
We did some testing on the XML with the SAXSample class and we
noticed that the error is related to the use of Entity
References. When we removed the Entity Reference ' the XML
was parsed correctly.
We also noticed that if we cut the XML in two smaller parts it
was also parsed correctly.
I attached the output of the parser, as well as the output of
the SAXSample class.
I hope you can fix this problem!
With kind regards,
Rolf van Deursen.
nullUpdate: I have attempted to use xmlparserv2.jar dated 12/23/08 that is packaged with jDeveloper 11g preview, but am still receiving the same message.
-
Help: DTD only partially validating XML file
Following are a small XML file I wrote and its accompagning DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE userSettings SYSTEM "userSettings.dtd">
<userSettings>
<pref name = "language" type = "string" value="EN" />
<pref name = "defaultfont" type = "string" value = "Arial" />
<pref name = "defaultPageWidth" type = "number" value = "595" />
<pref name = "defaultPageHeight" type = "number" value = "841" />
</userSettings>DTD:
<!ELEMENT userSettings (pref+)>
<!ELEMENT pref EMPTY>
<!ATTLIST pref
name CDATA #REQUIRED
type (string | number) #REQUIRED
value CDATA #REQUIRED
>So the attribute "type" of the element "pref" can only be either a number or a string. But if i write "sting" for example, the DTD does not issue an error. I know the DTD is working since changing the root element for instance does generate errors.
Anyone has a clue to why is my DTD only partially validating my XML file?Hello!
This is a simple example in Sun jdk 1.4.2.
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import java.io.File;
public class DTDValidator extends DefaultHandler {
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
DTDValidator myHandler = new DTDValidator();
File file = new File("my.xml");
parser.parse(file, myHandler);
} catch (Exception e) {
e.printStackTrace();
public void error(SAXParseException e) throws SAXException {
super.error(e);
System.out.println(e.getMessage());
public void fatalError(SAXParseException e) throws SAXException {
super.fatalError(e);
System.out.println(e.getMessage());
}Result:
Value "sting" is not one of the enumerated values for this attribute. -
Problem validating XML file with external schema file
Hi All
I am having trouble at the moment trying to validate an xml file using an external xsd file that sits on my server. I have followed the basic option but at the moment to no avail. I am using a DOMParser and am setting all the features and properties correctly ... well I think I am anyway.....below is a fragment of the code
DOMParser parser = new DOMParser ();
// Setting the validation on for the parser.
parser.setFeature ( "http://xml.org/sax/features/validation", true );
parser.setFeature ( "http://apache.org/xml/features/validation/schema", true);
parser.setProperty ( "http://apache.org/xml/properties/schema/externalnoNamespaceSchemaLocation", "c://testing.xsd" );
parser.setErrorHandler ( this );
I am getting an error telling me that the root element cannot be found.....see below
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'mainhome'.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNamespaceBinder.handleStartElement(Unknown Source)
at org.apache.xerces.impl.XMLNamespaceBinder.startElement(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$ContentDispatcher.scanRootElementHook(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at com.cibenix.aps.util.MenuXMLParser.process(MenuXMLParser.java:163)
at com.cibenix.aps.actions.MenuAddAction.execute(MenuAddAction.java:80)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2417)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:193)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:781)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:549)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:589)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:666)
Any help would be greatly appreciated
thanksIn the schema root element xs:schema add namespace declaration.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
In the XML document root element add xmlns:xsi and xsi:noNamespaceSchemaLocation attributes.
<root_element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file://c:/testing.xsd"> -
Validating XML files and generating error codes
I want to validate an XML file with a schema & also get hold of the fields/attributes/tags
that caused an error and generate error codes based on that. Any suggestion on
how this can be done. DOM, SAX allow to do validation but how do I know exactly
know which tags caused errors. We have to track the errors codes."SP" <[email protected]> wrote:
Use the HandlerBase class for getting hold of the tags and its attributes.
The methods in this class take the tags and attributes and throw the
SAXException. You can use these methods to find out which tag is throwing
an
exception.
Hope this helps
SP
I am using the DOMParser.parse method with the xerces parser. I have an error
handler registered to get hold of the errros. What happens is the parsing stops
at the first instance of an error. I want to continue parsing to get hold of all
errors. How can I achieve that?
>
"leena" <[email protected]> wrote in message
news:[email protected]..
I want to validate an XML file with a schema & also get hold of thefields/attributes/tags
that caused an error and generate error codes based on that. Anysuggestion on
how this can be done. DOM, SAX allow to do validation but how do Iknow
exactly
know which tags caused errors. We have to track the errors codes. -
Problem validating xml file - jaxb
hi people, I'm working with jaxb to generate Java source classes from the .xsd schemas that I have. I work with 17 schemas that, a priori, I can't modify. In those schemas there are a lot of types and structures that I can use when creating an .xml file. I've read other threads with the problem of namespaces but as a solution they provide a modification on the schemas. The generation of java source is ok, I've done custoization classes and no problem, but when I try to unmarshal an input xml file I get an error of validation:
DefaultValidationEventHandler: [ERROR]: Probably namespace URI of tag "XFFile" is wrong (correct one is "http://ww........
A possible xml file is :
<?xml version="1.0" encoding="UTF-8" standalone="no" ?><!DOCTYPE XFFile><XFFile xmlns:rp210Elements="http://www.smpte-ra.org/schemes/434/200X/multiplex/S377M/2004" xmlns:s377mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S377M/2004" xmlns:s377mMux="http://www.smpte-ra.org/schemes/434/200X/multiplex/S377M/2004" xmlns:s377mTypes="http://www.smpte-ra.org/schemes/434/200X/types/S377M/2004" xmlns:s380mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S380M/2004" xmlns:s381mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S381M/200X" xmlns:s382mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S382M/200X" xmlns:s385mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S385M/2004" xmlns:s422mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S422M/200X" xmlns:s422mTypes="http://www.smpte-ra.org/schemes/434/200X/types/S422M/200X" xmlns:s423mGroups="http://www.smpte-ra.org/schemes/434/200X/groups/S423M/200X">
<s380mGroups:ClipFramework rp210Elements:InstanceID="a6.67.7a.47.19.2f.4b.10.8f.ee.1e.59.6d.4c.f1.70" rp210Elements:LinkedGenerationID="0e.10.a8.9c.96.1c.4c.11.b1.fb.0a.a9.40.22.a4.e2">
<rp210Elements:ClipCreationDateTime>
<rp210Elements:Year>2006</rp210Elements:Year>
<rp210Elements:Month>4</rp210Elements:Month>
<rp210Elements:Day>18</rp210Elements:Day>
<rp210Elements:Hour>12</rp210Elements:Hour>
<rp210Elements:Minute>0</rp210Elements:Minute>
<rp210Elements:Second>0</rp210Elements:Second>
<rp210Elements:mSec4>0</rp210Elements:mSec4></rp210Elements:ClipCreationDateTime>
<rp210Elements:FrameworkExtendedTextLanguageCode>fr</rp210Elements:FrameworkExtendedTextLanguageCode>
</s380mGroups:ClipFramework>
</XFFile>
I think it's ok because someone has provided it to my company but I can't validate it because it takes elements from many schemas (am I wrong and I can?)
i can't post the schemas because of the copyrights (damn it). I'm not asking for a solution but if someone has an idea or has had a similar problema.. I'll appreciate all comments, thanks
Jordi
Message was edited by:
WuWeiIn the schema root element xs:schema add namespace declaration.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
In the XML document root element add xmlns:xsi and xsi:noNamespaceSchemaLocation attributes.
<root_element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file://c:/testing.xsd"> -
Validating xml-files inside jar-files for JWS
I want to use xml-files inside a jar-file and want to validate them with dtd-files,
located in the same jar-file. This does work, but only as long as the dtd-file is
in the same directory as the xml-file.
For example, I have no problem, with a DOC Type-statement like
<!DOCTYPE questestinterop SYSTEM "ims_qtiv1p1.dtd" >
With this statement, however, one needs an approprate dtd in every directory containing an XML-file of that type.
If however i want to gather the necessary dtd's in a directory one (or more) levels above with a DOCTYPE-statement of the form
<!DOCTYPE questestinterop SYSTEM "../ims_qtiv1p1.dtd" >
I get error messages of the form
java.io.FileNotFoundException: JAR entry Mikro/Marshall/BookQuestions/../ims_qtiv1p1.dtd not found in C:\Dokumente und Einstellungen\wreiss\Anwendungsdaten\Sun\Java\Deployment\javaws\cache\http\Dwiwi.upb.de\P80\DM~vwl08\DMOViSS\DMoviss_current\RMMikro.jar
at org.apache.crimson.parser.Parser2.fatal(Unknown Source)
at org.apache.crimson.parser.Parser2.externalParameterEntity(Unknown Source)
at org.apache.crimson.parser.Parser2.maybeDoctypeDecl(Unknown Source)
at org.apache.crimson.parser.Parser2.parseInternal(Unknown Source)
at org.apache.crimson.parser.Parser2.parse(Unknown Source)
at org.apache.crimson.parser.XMLReaderImpl.parse(Unknown Source)
at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at oviss.competenceCenter.XMLExpert.setElements(XMLExpert.java:245)
though the dtd-file is in the parent-directory (inside the jar) and the unpacked xml-file can be successfully validated.
Why does this happen. How can one use a single dtd for multiple xml-files (of the same type) in different directories?.
Thanks
Winfried ReissIn reply to myself, replacing the HTMLBrowser constructor with this;
public HTMLBrowser()
URL url;
try
// Construct the URL
url= this.getClass().getResource('/'+dir+'/'+startPage);
setPage(url);
catch (Exception e)
System.out.println( "Problem setting help homepage");
setEditable(false);
addHyperlinkListener(new LinkListener(this));
}made it work. This is because seemingly you need '/' at the start of the resouce's path and '/' as the separator, regardless of platform.
I hope this helps someone else.
John -
SAX and XML file, how to?
Hi,
I'm going to use JAXP and SAX to read my application XML config file.
But I'm lost, I don't know how to read the elements.
How does it function, do I have to put in the startElement() method as many "if" as entitys I need to process?
And how can I guess if an element belongs (is inside) one element or another?
Example:
<program>
<printer id="xx" type="aa">
<path> /aa/cc </path>
</printer>
<source>
<path> /aa/bb </path>
</source>
</program>
for this XML, how would you code it? this way?
startElement (String uri, String localName, String qName, Attributes attributes) {
if (localname.equals("printer")) {
//get printer attributes
} else if (localname.equals("source")) {
//get source attributes
thanks!i have one sample code through which u can read the elements from xml file.
// File SaxLister.java
import java.io.IOException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class SAXLister {
public static void main(String[] args) throws Exception
new SAXLister(args);
public SAXLister(String[] args) throws SAXException, IOException
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
// should load properties rather than hardcoding class name
parser.setContentHandler(new PeopleHandler( ));
parser.parse(args.length == 1 ? args[0] : "parents.xml");
/** Inner class provides DocumentHandler
class PeopleHandler extends DefaultHandler
boolean parent = false;
boolean kids = false;
public void startElement(String nsURI, String localName,
String rawName, Attributes attributes) throws SAXException {
// System.out.println("docEvents" + "startElement: " + localName + ","
// + rawName);
// Consult rawName since we aren't using xmlns prefixes here.
if (rawName.equalsIgnoreCase("name"))
parent = true;
if (rawName.equalsIgnoreCase("children"))
kids = true;
public void characters(char[] ch, int start, int length) {
if (parent) {
System.out.println("Parent: " + new String(ch, start, length));
parent = false;
} else if (kids) {
System.out.println("Children: " + new String(ch, start, length));
kids = false;
/** Needed for parent constructor */
public PeopleHandler( ) throws org.xml.sax.SAXException {
super( );
// File people.xml
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>http://www.darwinsys.com/</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">afd@node1</email>
<country>Canada</country>
</person>
</people>
I hope this gives u a better understanding of how SAX parser works..
Kindly note u need xml.jar and xerces.jar in ur classpath to run above program.
Regards,
Nikunj
Maybe you are looking for
-
Bluetooth not recognized after upgrading to 6.0 BIOS version
Hi, I previously had 5.5 BIOS version on my [PSAA8] notebook and all was fine. Just right a moment ago I've updated to 6.0 version and Bluetooth doesn't work. I wonder where I could find the old 5.5 version, no search can get me so far. Any help appr
-
just got an ipod nano 2 gig from santa and found that i can't use it with my computer. i have a HP Pavillion Home Edition Version 2002, 2.10 GHz, 448 MB of Ram, service pack 2, using Windows XP. The ipod specs ask for a service pack 4. I asked HP wha
-
JDev WS proxy not sending username and password
Hi all, I've created a short web service which requires username authentication and testing it on the browser, the web service works fine. I then tried to create a web proxy (which is the new term for Web Service Stub in JDeveloper Studio Edition 10.
-
Creative DMPLX 200: format default.rom miss
I got my MP3 Player for Christmas last year, so it's only a few months old. Yesterday I deleted all the music files from it and then went to charge and create my playlist on the computer and after connecting my device to the USB cable, I was asked to
-
Query related to form printing.
Hello sir's, In program i am giving delivery number as input ,if there is 10 items in that delivery number, then i want each item to be printed on the separate page in smartform on a single print click. There is no limit on number of items in particu