powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / XSD Validation
2 сообщений из 2, страница 1 из 1
XSD Validation
    #34464673
Guiest
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Здравствуйте!

Надо узнать проходит ли данный xml файл, валидацию по данному xsd файлу.
Не подскажете, как просто и эффективно реализовать такое под jdk-1.4 ?

Заранее спасибо.
...
Рейтинг: 0 / 0
XSD Validation
    #34470116
Denis Bessmertnyj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
С своё время я написал для себя такую вот программу

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
 package  validator;

 import  java.io.File;
 import  java.io.IOException;

 import  java.awt.BorderLayout;
 import  java.awt.Dimension;
 import  java.awt.GridBagConstraints;
 import  java.awt.GridBagLayout;
 import  java.awt.Insets;
 import  java.awt.Toolkit;
 import  java.awt.Container;
 import  java.awt.event.ActionEvent;
 import  java.awt.event.ActionListener;

 import  javax.swing.JFileChooser;
 import  javax.swing.JFrame;
 import  javax.swing.JLabel;
 import  javax.swing.JPanel;
 import  javax.swing.JScrollPane;
 import  javax.swing.JTextArea;
 import  javax.swing.JTextField;
 import  javax.swing.ScrollPaneConstants;
 import  javax.swing.JButton;
 import  javax.swing.BorderFactory;
 import  javax.swing.border.Border;

 import  javax.xml.XMLConstants;
 import  javax.xml.parsers.DocumentBuilder;
 import  javax.xml.parsers.DocumentBuilderFactory;
 import  javax.xml.parsers.ParserConfigurationException;
 import  javax.xml.transform.dom.DOMSource;
 import  javax.xml.validation.Schema;
 import  javax.xml.validation.SchemaFactory;
 import  javax.xml.validation.Validator;

 import  org.w3c.dom.Document;
 import  org.xml.sax.SAXException;

 public   final   class  XMLValidator {

     private   static   final  String GUI_INTERFACE_COMMAND = "-gui";
    
     public   static   void  main(String[] args) {
         if (args.length >  0 ) {
             if (args[ 0 ].equalsIgnoreCase(GUI_INTERFACE_COMMAND)) {
                 showGUIInterface();                                
            }
             else  {
                  try  {
                    File xmlFile =  new  File(args[ 0 ]);
                    File xmlSchemaFile =  new  File(args[ 1 ]);
                    processing(xmlFile, xmlSchemaFile);
                    System.out.println("Document is valid");
                 }
                  catch (Exception e) {
                    System.out.println(e.getMessage());
                 }
            }
        }
         else  {
            System.out.println("Wrong input parameters");
            System.out.println("The first parameter must be XML Document and the second - XML Schema");
            System.out.println("You may use GUI by specifing " + GUI_INTERFACE_COMMAND + " key");
        }       
    }

     private   static   void  showGUIInterface()
    {
         final  JFileChooser fileChooser =  new  JFileChooser();
        fileChooser.setFileFilter( new  javax.swing.filechooser.FileFilter() {
             public   boolean  accept(File file) {
                String fileName = file.getName();
                 return  file.isFile() && (fileName.endsWith("xml") || fileName.endsWith("xsd"));
            }
            
             public  String getDescription() {
                 return  "XML Documents & Schemas";
            }
        });
        
         final  JTextArea logTextArea =  new  JTextArea();
        logTextArea.setLineWrap(true);
        logTextArea.setWrapStyleWord(true);

         final  JFrame frame =  new  JFrame("Quick XML Validator");     
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
         final   int  FRAME_WIDTH =  496 ;
         final   int  FRAME_HEIGHT =  282 ;

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenDimension = toolkit.getScreenSize();

         int  screenWidth = ( int ) screenDimension.getWidth();
         int  screenHeight = ( int ) screenDimension.getHeight();
        
        frame.setBounds((screenWidth - FRAME_WIDTH) /  2 ,
                        (screenHeight - FRAME_HEIGHT) /  2 ,
                        FRAME_WIDTH,
                        FRAME_HEIGHT);

        GridBagLayout gridBagLayout =  new  GridBagLayout();
        GridBagConstraints gridBagConstraints =  new  GridBagConstraints();
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.insets =  new  Insets( 2 ,  2 ,  1 ,  1 );
        gridBagConstraints.weightx =  0 ;        

         final   int  FILE_TEXT_FIELD_SIZE =  25 ;        

        Border emptyBorder = BorderFactory.createEmptyBorder( 7 ,  7 ,  7 ,  7 );
        
        
        JPanel componentsPanel =  new  JPanel(gridBagLayout);
        componentsPanel.setBorder(emptyBorder);
        
        JLabel xmlFileLabel =  new  JLabel("XML File:");
        gridBagLayout.addLayoutComponent(xmlFileLabel, gridBagConstraints);
        componentsPanel.add(xmlFileLabel);
        
         final  JTextField xmlTextField =  new  JTextField(FILE_TEXT_FIELD_SIZE);        
        xmlTextField.setMinimumSize(xmlTextField.getPreferredSize());
        gridBagLayout.addLayoutComponent(xmlTextField, gridBagConstraints);
        componentsPanel.add(xmlTextField);
        
        JButton chooseXMLFileButton =  new  JButton("Choose...");
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagLayout.addLayoutComponent(chooseXMLFileButton, gridBagConstraints);        
        componentsPanel.add(chooseXMLFileButton);        
        chooseXMLFileButton.addActionListener( new  ActionListener()
                                              {
                                                     public   void  actionPerformed(ActionEvent event)                                                    {
                                                         int  openResult = fileChooser.showOpenDialog(frame);
                                                         if (openResult == JFileChooser.APPROVE_OPTION) {
                                                            xmlTextField.setText(fileChooser.getSelectedFile().getPath());
                                                        }
                                                         else   if (openResult == JFileChooser.ERROR_OPTION) {
                                                            logTextArea.setText("error occured while opening xml file");
                                                        }                                                        
                                                    }
                                              });
        
        
        JLabel xmlSchemaLabel =  new  JLabel("XML Schema File: ");
        gridBagConstraints.gridwidth =  1 ;
        gridBagLayout.addLayoutComponent(xmlSchemaLabel, gridBagConstraints);
        componentsPanel.add(xmlSchemaLabel);
        
         final  JTextField xmlSchemaTextField =  new  JTextField(FILE_TEXT_FIELD_SIZE);        
        xmlSchemaTextField.setMinimumSize(xmlSchemaTextField.getPreferredSize());
        gridBagLayout.addLayoutComponent(xmlSchemaTextField, gridBagConstraints);
        componentsPanel.add(xmlSchemaTextField);
        
        JButton chooseXMLSchemaFileButton =  new  JButton("Choose...");
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagLayout.addLayoutComponent(chooseXMLSchemaFileButton, gridBagConstraints);
        componentsPanel.add(chooseXMLSchemaFileButton);
        chooseXMLSchemaFileButton.addActionListener( new  ActionListener()
                                                    {
                                                         public   void  actionPerformed(ActionEvent event)                                                    {
                                                             int  openResult = fileChooser.showOpenDialog(frame);
                                                             if (openResult == JFileChooser.APPROVE_OPTION) {
                                                                xmlSchemaTextField.setText(fileChooser.getSelectedFile().getPath());
                                                            }
                                                             else   if (openResult == JFileChooser.ERROR_OPTION) {
                                                                logTextArea.setText("error occured while opening xml file");
                                                            }                                                        
                                                        }
                                                    });

        
        JButton validateButton =  new  JButton("Validate");
        gridBagConstraints.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        gridBagConstraints.insets =  new  Insets( 11 ,  0 ,  11 ,  0 );
        gridBagLayout.addLayoutComponent(validateButton, gridBagConstraints);
        componentsPanel.add(validateButton);        
        validateButton.addActionListener( new  ActionListener()
                                         {
                                             public   void  actionPerformed(ActionEvent event) {
                                                File xmlFile =  new  File(xmlTextField.getText());
                                                File schemaFile =  new  File(xmlSchemaTextField.getText());
                                                 try  {
                                                    processing(xmlFile, schemaFile);
                                                    logTextArea.setText("Document is valid");
                                                }
                                                 catch (Exception e) {
                                                   logTextArea.setText(e.getMessage());
                                                }                                                
                                            }                                            
                                        });
                
        gridBagConstraints.insets =  new  Insets( 2 ,  2 ,  1 ,  1 );
        
        JScrollPane textAreaScrollPane =  new  JScrollPane(logTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
        gridBagConstraints.fill = GridBagConstraints.BOTH;        
        gridBagConstraints.weighty  =  1 ;
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;        
        gridBagLayout.addLayoutComponent(textAreaScrollPane, gridBagConstraints);
        componentsPanel.add(textAreaScrollPane);
        
        Container contentPane = frame.getContentPane();
        contentPane.add(componentsPanel, BorderLayout.CENTER);
               
        frame.setVisible(true);             
    }


     private   static   void  processing(File xmlFile, File schemaFile)  throws  Exception {
            Document xmlDocument = getXMLDocument(xmlFile);
            Validator schemaValidator = getSchemaValidator(schemaFile);
            DOMSource domSource =  new  DOMSource(xmlDocument);
            schemaValidator.validate(domSource);
    }
    
     private   static  Document getXMLDocument(File xmlFile) 
                               throws  ParserConfigurationException, 
                                 IOException,
                                 SAXException {
        
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);         
        DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
        Document xmlDocument = docBuilder.parse(xmlFile);
        
         return  xmlDocument;
    }

     private   static  Validator getSchemaValidator(File schemaFile) 
                                 throws  SAXException {
        
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaObj = factory.newSchema(schemaFile);
        Validator validator = schemaObj.newValidator();
        
         return  validator;
    }
    
}
...
Рейтинг: 0 / 0
2 сообщений из 2, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / XSD Validation
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]