Validationerror with JDOM!

Hi,
I try to validate XMLs against XSD with SAXBuilder. It looks fine as long as there are no stylesheet information in xmls.
e.g. for a document that fails the validation:
<?xml version="1.0"?>
<?xml:stylesheet href="file.xsl" type="text/xsl"?>
<myTag>bla bla</myTag>
I get this error-msg:
IllegalTargetException: IllegalTargetException is thrown when a target is supplied in construction, etc., of a JDOM ProcessingInstruction, and that name breaks XML naming conventions.
same document without having ?xml:stylesheet information works fine:
<?xml version="1.0"?>
<myTag>bla bla</myTag>
What is the problem?

I already got the solution.
In the XML, it should be
<?xml-stylesheet href="file.xsl" type="text/xsl"?>
instead of
<?xml:stylesheet href="file.xsl" type="text/xsl"?>
Thanks!

Similar Messages

  • XML validation with JDOM / JAXP

    Hello,
    I am trying to validate xml file against schema file. I decided to use JDOM and JAXP.
    First question: is it a good choice?
    I did a first attempt but not sure I have understood all what I am doing :(
    First I have create a parser usinf org.jdom.*
    SAXBuilder parser = new SAXBuilderThen I built my document:
    Document doc = parser.build(myFile)These 2 steps are ok. But it does not do validation.
    I saw in the JDOM documentation that I can set a validation flag to true. I did it. First problem, I got the following error from JDOMException: Document is invalid: no grammar found.
    Is there a way to specify to the parser where to find the xsd file?
    As I did not find answer to this question by myself, I tried implementing the Schema class from JAXP:
    SAXBuilder parser = new SAXBuilder;
    Document doc = parser.build(myFile);
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
    ValidatorHandler vh = schema.newValidatorHandler();
    SAXOutputter so = new SAXOutputter(vh);
    so.output(doc);It does the validation against the schema file specified but I am not really sure about what I am doing here. The last 2 commands are not clear to me :(
    Then in my schema file, I have elements that have default value. I expected the following behavior: if the element is not in the xml file then the default will be used by the parser (and added in the tree). But it seems, it's not the case.
    Any help/explanation will be really appreciated.

    I am trying to validate xml file against schema file. I decided to use JDOM and JAXP.
    First question: is it a good choice?
    If only schema validation is required use the validation API in JDK 5.0.
    http://www-128.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html
    http://java.sun.com/developer/technicalArticles/xml/validationxpath/
    For validation with JDOM, the following validation application explains the procedure:import org.jdom.input.SAXBuilder;
    import org.xml.sax.SAXException;import org.jdom.*;
    import java.io.*;
    public class JDOMValidator{
    public void validateSchema(String SchemaUrl, String XmlDocumentUrl){
               try{
    SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser",true);<br/>saxBuilder.setValidation(true);
    saxBuilder.setFeature("http://apache.org/xml/features/validation/schema",true);
    saxBuilder.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
    saxBuilder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",SchemaUrl);
    Validator handler=new Validator();
    saxBuilder.setErrorHandler(handler);
    saxBuilder.build(XmlDocumentUrl);
    if(handler.validationError==true)
    System.out.println("XML Document has Error:"+handler.validationError+""+
    handler.saxParseException.getMessage());      
    else           
          System.out.println("XML Document is valid");
              }catch(JDOMException jde){
                }catch(IOException ioe){
    private class Validator extends DefaultHandler{     
         public boolean  validationError = false; 
         public SAXParseException saxParseException=null;    
      public void error(SAXParseException exception) throws SAXException{        
         validationError =true;
         saxParseException=exception; 
      public void fatalError(SAXParseException exception) throws SAXException  {
    validationError = true;     
    saxParseException=exception;
      public void warning(SAXParseException exception) throws SAXException       {
    public static void main(String[] argv)   {
       String SchemaUrl=argv[0];StringXmlDocumentUrl=argv[1];
       JDOMValidator validator=new JDOMValidator();
       validator.validateSchema(SchemaUrl,XmlDocumentUrl);
    }

  • Problem with JDOM and schemas

    I'm trying to parse (and validate) an XML document with JDOM.
    My root element is declared in the schaema whixh is asociated to the document.
    But during parsing, an exception saying that my root element is not declared is thrown.
    Can someone axplain to me what can happen ?
    Thank's

    What's this element ?
    My schema is indicated by the xsi:schemeLocation attribute of my root-element .

  • Modifying XML files with JDOM

    Hi:
    I've been trying to get up to speed with JDOM, and while it seems pretty intuitive, I've been having a problem w/ modifying XML documents.
    Namely, once I get a Document object from a (skeleton) XML file, do changes made to the Document object through, say, addContent() propagate to the original file? My gut feeling is no, although this was certainly what I had expected initially.
    Here's a code fragment of what I had tried to do to populate a barebones XML file:
                   Document doc = builder.build(output);
              // add 100 elements, all the same
              for (int count = 0; count < 100; count++)
                   Element curr = new Element("book");
                   // create child nodes for book
                   Element title = new Element("title");
                   title.addContent("Book " + (count + 1));
                   Element author = new Element("author");
                   author.addContent("Author " + (count + 1));
                   Element price = new Element("price");
                   price.addContent("Price " + (count + 1));
                   curr.addContent(title);
                   curr.addContent(author);
                   curr.addContent(price);
                   doc.getRootElement().addContent( curr );
              }

    Mikael,
    This sounds like one of the many quirks (perhaps bugs) related to how FrameMaker handles non-FM files in books. The current book model doesn't play well with XML files as chapters and this seems like yet another problem. Apparently, if an xref does not target another .fm file in the book, Frame assumes that the target file is not in the book and therefore will not be in the book PDF.
    There have been discussions here about this in the past. The solution that I use is to run an API client before publishing that converts all XML files to .fm files, and redirect all xrefs appropriately. Then, book features work as expected and PDFs come out as normal. This is not feasible, however, without the automation from the API client.
    There may be some who would say that the best approach is to use XML and books the way that the designers did account for... that is, the whole book becomes an XML document with entity references to the separate chapters. In my work, though, this model was not appropriate... rather, I needed a binary FM book to act like a book, except with XML files as chapters. So, I think I understand your situation.
    Is API programming or FrameScript an option for you? I think it may be the only way to get what you are looking for.
    Russ

  • Please, if you have ever used schemas with JDOM !!!!!!

    How can we validate a document which refers to a schema rather than a DTD with JDOM ?
    I tried to do that but an error occured, telling to me that my root element isn't declared.
    Can someone help me ?

    Hi,
    If you want more information, go to this web page :
    http://www.jdom.org/docs/faq.html
    There is an answer to your question.

  • Urgent :::::.i WISH TO DO THIS WITH JDOM and JAVA .

    file A.XML
    <XML>
    <TP>
    <FF>
    </FF>
    </TP>
    </XML>
    file B.XML
    <XML>
    <TP>
    <GG>
    </GG>
    </TP>
    </XML>
    I WANT TO PASTE node GG in b.xml to a.xml like this
    <XML>
    <TP>
    <FF>
    <GG>
    </GG>
    </FF>
    </TP>
    </XML>
    i WISH TO DO THIS WITH JDOM and JAVA .
    Please let me know how to do this ....
    i dont want to use XSL OR XSLT ...
    i am free for discussions...pls help me
    ciao

    You can try these steps in case of issues with web pages:
    Reload web page(s) and bypass the cache to refresh possibly outdated or corrupted files.
    *Hold down the Shift key and left-click the Reload button
    *Press "Ctrl + F5" or press "Ctrl + Shift + R" (Windows,Linux)
    *Press "Command + Shift + R" (Mac)
    Clear the cache and cookies only from websites that cause problems.
    "Clear the Cache":
    *Firefox/Tools > Options > Advanced > Network > Cached Web Content: "Clear Now"
    "Remove Cookies" from sites causing problems:
    *Firefox/Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do NOT click the Reset button on the Safe Mode start window.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes

  • Better with JDom or not?

    Hello, I have one function to create a XML structure without use JDom. I read my strings and I create a Xml. It's difficult but I have already done. But my question is if it's easyer use JDom and create a new function.
    Here my String
    Name
    Name.Surname
    Name.Surname,Second
    Name.Surname.First
    Name2
    Name.Surname
    Name2.Surname.Folder
    Name2.Structure
    I want this Xml:
    <Cuenta id="xx" label="xx1">
    <node label="Borrador"></node>
    <node label="Name">
        <node label="Surname">
                  <node label="Second"</node>
                  <node label="First"></node>
        </node>
    </node>
    <node label="Name2">
        <node label="Surname">
                  <node label="Folder"</node>
        </node>
        <node label="Structure"></node>
    </node>
    </Cuenta>Exist any easy way to do that? Or it's better if I continue with my method(it's difficult and if I have to change something I have to change a lot of things. I want one function to create that dinamicaly, not always is the same list. My function do dinamicaly but it's not very clear for other people.
    Thanks!

    Now I'm creating manually and then I use JDom to transform to Xml and edit if I have to change something. You said that you would use JDom to create. To say the truth I'm a newbie with JDom, and I know how can create a very simple document, but not how can create this Xml starting with my list. I have to use split to separate the folders and ..... but I don't know how can create the Xml.
    Now I have my old solution but if you see easy that this function using JDom, can you say me how can I do or some      
    recommendations. Or if you show veryvery easy you can put the code, just kidding, hahaha (don't worry it's enough with some recomendations).
    This is my actual code, has you can see it's a little complicate, I think that with JDom the code will be much more understandable.
    public static String crearStringXML(lista) throws MessagingException, IOException
                    java.util.Collections.sort(lista);//order the lsit
                   String textOut="<Cuenta id=\"cuenta"+id+"\" label=\""+user+"\">";
                   String[] oldPath = new String[0];
                   String[] newPath=null;
                   for(String path : lista) {
                        newPath = path.split("\\.");//dvide the folders
                      int matchLen = 0;
                      // To calculate how many are the same
                      while(matchLen < oldPath.length && matchLen < newPath.length && oldPath[matchLen].equals(newPath[matchLen]))
                              matchLen++;
                      for(int i = matchLen; i < oldPath.length; i++) {
                           textOut += "</node>";
                      for(int i = matchLen; i < newPath.length; i++){
                         textOut += "<node label=\"";
                         textOut += newPath[i]+"\">";
                     oldPath = newPath;
                   for(int i =0;i< newPath.length;i++)
                        textOut +="</node>";
                   textOut += "</Cuenta>";
                   return textOut;
              }Thanks!

  • Transformation with JDOM (off-topic)

    Hi All,
    I am wondering if anyone could advice me on how to carry out transformation in a JDOM enviornment. I am familiar with querrying data using XPath with JDOM.
    Any tutorial or online reference material would be very much appreciated.
    I am running Netbeans 6.1, J2EE 5 Glassfish on Windows XP platform.
    Many thanks,
    Jack

    It contains the [org.jdom.transform|http://www.jdom.org/docs/apidocs/org/jdom/transform/package-summary.html] package with classes to do basic transformation. As the documentation says:
    Classes to help with transformations, based on the JAXP TrAX classes. JDOMTransformer supports simple transformations with one line of code. Advanced features are available with the JDOMSource and JDOMResult classes that interface with TrAX.

  • Can i do this with jdom

    Hi
    i need to open an xml file, then modify it and then put its content into a string without modifying the physical file.
    Can i do this with jdom?
    I know that i can use some methods to build an object from a physical file, and also modify it, but then can i get the full content and put it into a string?
    Thanks

    Yep, you can do that with JDOM. U can use org.jdom.output.XMLOutputter to put the modified contents into a String. (Using a StringWriter)

  • How To read an XML file with JDom

    I have read through some tutorials after installing JDom on how to read an existing XML file and I was confused by all of them. I simply want to open an XML file and read one of the node's content. Such as <username>john doe</username> this way I can compare values with what the user has entered as their username. I am not sure were to start and I was hoping someone could help me out.
    I know that this seems like an insecure way to store login information but after I master opening and writing XML files with JDom I am going to use AES to encrypt the XML files.

    Here is a test program for JDom and XPath use considering your XML file is named "test.xml" :import org.jdom.input.*;
    import org.jdom.xpath.*;
    public class JDomXPath {
    public static void main(String[] args) {
      SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
      try {
       org.jdom.Document jdomDocument = saxBuilder.build("test.xml");
       org.jdom.Element usernameNode = (org.jdom.Element)XPath.selectSingleNode(jdomDocument, "//username");
       System.out.print(usernameNode.getText());
      } catch (Exception e) {
       e.printStackTrace();
    }(tested with Eclipse)

  • XSLT usage with JDOM problem

    When I try to do an XSL transformation on a JDOM tree
    using Oracle's xml classes from xmlparserv2.jar (includes
    the javax.xml.transform api) I get the following:
    java.lang.ClassCastException: org.jdom.transform.JDOMSource$DocumentReader
         at oracle.xml.jaxp.JXTransformer.transform(JXTransformer.java:201)
    The same code works with xalan/crimson as well as saxon/aelfred, anyone
    seen this and knows a solution? Code snippet:
    private Frame transform(Document in, URL stylesheet) {
         TransformerFactory f = TransformerFactory.newInstance();
         InputStream s = stylesheet.openStream();
         Transformer transformer = f.newTransformer(new StreamSource(s));
         JDOMResult out = new JDOMResult();
         out.setFactory(new FPLNodeFactory());
         transformer.transform(new JDOMSource(in), out);
         s.close();
         return (Frame)out.getDocument().getRootElement().detach();
    I was wondering if there is a problem with the Oracle's impelmentation or am I using it incorrectly.
    Thanks.
    Suhas.

    This forum is mostly reviewed by folks using the XML features in the database (which basically means version 9.2). This is an XDK question--I would post it to Technologies > XML > General.

  • Intresting problem with JDOM and xmlns in root element.

    Hi all,
    I am trying to parse a xml file using a jdom java code.This code works fine if I remove xmlns attribute in the root element.Please tell me how to fix this issue.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Xml
    <process name="CreateKBEntryService" targetNamespace="http://serena.com/CreateKBEntryService" suppressJoinFailure="yes" xmlns:tns="http://serena.com/CreateKBEntryService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" xmlns:bpelx="http://schemas.oracle.com/bpel/extension" xmlns:ora="http://schemas.oracle.com/xpath/extension" xmlns:nsxml0="http://localhost:8080/axis/services/CreateKBEntryService" xmlns:nsxml1="http://DefaultNamespace" xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/">
    <partnerLinks>
              <partnerLink name="client" partnerLinkType="tns:CreateKBEntryService" myRole="CreateKBEntryServiceProvider"/>
              <partnerLink name="CreateKBEntryPartnerLink" partnerLinkType="nsxml0:CreateKBEntryLink" partnerRole="CreateKBEntryProvider"/>
         </partnerLinks>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    Java:
    import java.io.*;
    import java.util.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class sample1 {
    public static void main(String[] args) throws Exception {
    // create a XML parser and read the XML file
    SAXBuilder oBuilder = new SAXBuilder();
    Document oDoc = oBuilder.build(new File("file location "));
         Element root = oDoc.getRootElement();
         System.out.println(root.getName());
         String tgtns= root.getAttributeValue("targetNamespace");
         System.out.println("tgt ns "+ tgtns);
    List list= root.getChildren("partnerLinks");
         Iterator it1= list.iterator();
         System.out.println(list.size());
         while(it1.hasNext()){
              Element partnerlinks = (Element)it1.next();
              List list2= partnerlinks.getChildren("partnerLink");
              System.out.println(list2.size());
              Iterator it2= list2.iterator();
              String[][] partnerLinkval = new String [2][list2.size()];
              int i=0,j=0;
              while(it2.hasNext())
                   Element el2= (Element)it2.next();
              String ElementName = el2.getName();
              partnerLinkval[i][j]= ElementName;
              j++;
              String Attribute = el2.getAttributeValue("myRole");
              partnerLinkval[i][j]= Attribute;
              i++;
              j--;
              System.out.println("Saving in array "+el2.getName());
              System.out.println("Saving in array "+Attribute);
              System.out.println("array length"+partnerLinkval.length);
              for (int l=0;l<2;l++){
              for(int k=0;k<partnerLinkval.length;k++)
                   System.out.println(partnerLinkval[l][k]);
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Result:
    Without Xmlns in xml file
    process
    tgt ns http://serena.com/buildserviceflow
    1
    2
    Saving in array partnerLink
    Saving in array BpelServiceFlowProvider
    Saving in array partnerLink
    Saving in array null
    array length2
    partnerLink
    BpelServiceFlowProvider
    partnerLink
    null
    Result with xmlns:
    process
    tgt ns http://serena.com/CreateKBEntryService
    0

    Hi,
    I am also having the same problem using jdom, my code works fine when there is no xmlns attribute but when i put the xmlns attribute back in doesn't work.
    Did you manage to find a way to solve this problem?

  • Formatting problem with JDOM

    friends,
    help me out plz..
    While creating a xml document using JDOM ,
    I am not able to get the formatted xml file.
    program output is:
    <?xml version="1.0" encoding="UTF-8"?>
    <person><name>A</name><name>B</name><name>C</name><name>D</name></person>
    I want the result as:
    <?xml version="1.0" encoding="UTF-8"?>
    <person>
         <name>A</name>
         <name>B</name>
         <name>C</name>
         <name>D</name>
    </person>
    // XMLGenerator.java
    import org.jdom.Element;
    import org.jdom.Document;
    import org.jdom.output.XMLOutputter;
    import java.io.*;
    public class XMLGenerator {
    public static void main(String[] args) throws Exception{
    Element root = new Element("employee");
    while(rs.next()) // rs .. ResultSet
    Element emp_name= new Element("name");
    emp_name.setText(rs.getString(rs.getString("name")));
    root.addContent(emp_name);
    Document doc = new Document(root);
    // serialize it into a file
    try {
    FileOutputStream out = new FileOutputStream("record.xml");
    XMLOutputter serializer = new XMLOutputter();
    serializer .setIndent(true);
    serializer.output(doc, out);
    out.flush();
    out.close();
    catch (IOException e) {
    System.err.println(e);

    try:
    XMLOutputter serializer = new XMLOutputter( " " );
    with the size of the indent you require.
    You dont really need the line: serializer.setIndent(true); if u use this constructor.
    Hope this Helps
    Sam

  • Deserialization Problem with JDOM Document

    HI,
    I am using weblogic7.0 and i have created my own class which implements serializable. I set the object of this class in the ObjectMessage and send it across. Sometime i have to send some vector,sometimes string and sometime a XML document. So i can set these type of objects in my custom serializable object and send it. For sending XML , either i can send it as a string or as u said as Document object. But i want to do send it as a Document object. So i have created a an object of "org.jdom.Document" which implement serializable and setting this object into my custom object and sending this custom object in the objectmessage. But then weblogic throws some exceptions which has to do with deserialization.I am printing the exception below. (without the object of org.jdom.Document this custom object reaches safely and happily:))........can you or anybody tell me what could be the reason..
    weblogic.jms.common.JMSException: Error deserializing object
    at weblogic.jms.common.ObjectMessageImpl.getObject(ObjectMessageImpl.java:140)
    at com.sds.kb.cm.CMMDBReceiver.onMessage(CMMDBReceiver.java:143)
    at weblogic.ejb20.internal.MDListener.execute(MDListener.java:356)
    at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:290)
    at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:271)
    at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2303)
    at weblogic.jms.client.JMSSession.execute(JMSSession.java:2226)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    ----------- Linked Exception -----------
    weblogic.jms.common.JMSException: Error deserializing object
    at weblogic.jms.common.ObjectMessageImpl.getObject(ObjectMessageImpl.java:140)
    at com.sds.kb.cm.CMMDBReceiver.onMessage(CMMDBReceiver.java:143)
    at weblogic.ejb20.internal.MDListener.execute(MDListener.java:356)
    at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:290)
    at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:271)
    at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2303)
    at weblogic.jms.client.JMSSession.execute(JMSSession.java:2226)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    any help would be apprciated..
    Akhil

    Are you sure that your object gets serialized in the first place? You could use the writeObject method (explained in Javadoc for java.io.Serializable) to snoop the process.
    I am actually surprised you can serialize a DOM document.
    /Sebastian

  • Problem with JDOM and euro character

    Hi,
    I have an xml file including euro characters (�) and starting with :
    <?xml version="1.0" encoding="ISO-8859-15"?>
    as it should probably be.
    However, my problem is that (JDOM and) SAXBuilder doesn't recognize the euro characters and replace them by an unknown character '?'.
    What's wrong and how can I solve it?
    Thanks in advance.

    All right, this is a a part of my code:
    ....SAXBuilder builder = new SAXBuilder( true );
    //create the document
    //this doc contains this tag <RefVersion> data�data </RefVersion>
    Document doc = builder.build( "E:\\test.xml" );
    System.out.print( "before charAt = " + "�".charAt(0) + String.valueOf('\u20ac') );
    String str = "euro�euro";
    System.out.println( "euro�euro ->" + str.replace('\u20ac','O') );
    Element root = doc.getRootElement();
    //recup du noeud RefVersion
    Element version = root.getChild( "RefVersion" );
    str = version.getText();
    System.out.println( "nom= " + version.getName() + " data= " + str );
    System.out.println( "index de � ds euro�euro " + str.replace('\u20ac','O') );
    and the output is:
    before charAt = ��
    euro�euro ->euroOeuro
    nom= RefVersion data= data?data
    index de � ds euro�euro data?data
    So, obviously, it comes from JDOM.

Maybe you are looking for