Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Прикручивание DTD к SAX parser'y 
V
    Опции темы
Goganchic
Дата 9.12.2006, 20:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 678
Регистрация: 18.6.2004

Репутация: нет
Всего: 5



Есть код:
Код

public class XmlEngineClass extends DefaultHandler
{
    protected DefaultMutableTreeNode curUnit = new DefaultMutableTreeNode( "root" );
    
    /**
     * Parsing of document's begin
     */
    public void startDocument () throws SAXException
    {
        
    }
    
    /**
     * Parsing of document's end
     */
    public void endDocument ()
      throws SAXException
    {
        
    }
    
    /**
     * Parsing opening tag
     * @param uri some property, what I don't exectly know
     * @param localName tag name
     * @param gname some special tag name
     * @param attrs tag's properties
     */
    public void startElement( String uri, String localName, String gname, Attributes attrs)
    {
        DefaultMutableTreeNode tmp_c = new DefaultMutableTreeNode ( localName );
        PropertyTable pt = new PropertyTable ( localName );
        if ( attrs.getLength() != 0 )
        {
            for ( int i = 0; i < attrs.getLength(); i++ )
            pt.addProperty(attrs.getLocalName(i), attrs.getValue(i));
        }
        tmp_c.setUserObject(pt);
        curUnit.add(tmp_c);
        curUnit = tmp_c;
    }
    
    /**
     * Parsing closing tag
     * @param uri some property, what I don't exectly know
     * @param localName tag name
     * @param gname some special tag name
     */
    public void endElement ( String uri, String localName, String gname )
    {
        curUnit = (DefaultMutableTreeNode)curUnit.getParent();
    }
    
    /**
     * Parsing text between opening and closing tags
     * @param ch text array
     * @param offset text begin position
     * @param length text length
     */
    public void characters(char[] ch, int offset, int length)
    throws SAXException 
    {
        char tmp[] = new char[length];
        
        for ( int i = offset; i < offset + length; i++ )
        {
            tmp[i-offset] = ch[i];
        }
        
        String text_attr = new String (tmp);
        
        while ( text_attr.length() > 0 && 
                (text_attr.charAt(0) == ' ' || text_attr.charAt(0) == '\n') )
            text_attr = text_attr.substring(1);
        
        PropertyTable props = (PropertyTable)curUnit.getUserObject();
        
        for ( int i = 0; i < props.getSize(); i++ )
        {
            if ( props.getPropertyNameAt(i).equals("TEXT") )
            {
                text_attr = props.getPropertyValueAt(i).concat(text_attr);
                props.removePropertyAt(i);
                props.addProperty("TEXT", text_attr);
                return;
            }
                
        }
        
        if ( text_attr.length() > 0 )
            props.addProperty("TEXT", text_attr);
    }
    
    /**
     * Default constructor
     *
     */
    public XmlEngineClass ()
    {
        
    }
    
    /**
     * Saving to file
     * @param tree tree, which must be saved
     * @param fn name of saving file
     * @throws IOException
     */
    public void saveToFile ( DefaultMutableTreeNode tree, String fn )
    throws IOException
    {
        System.out.println ( "Saving to file" );
        BufferedWriter out =
             new BufferedWriter(
               new FileWriter(fn));
        out.write( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
        for ( int i = 0; i < tree.getChildCount(); i++ )
            saver ( (DefaultMutableTreeNode)tree.getChildAt(i), 0, out );
        out.close();
        System.out.println ("DEBUG: Document was saved successfuly");
    }
    
    /**
     * Saving one element
     * @param u saving element
     * @param tab tab of element or depth
     * @param out saving file stream
     * @throws IOException
     */
    protected void saver ( DefaultMutableTreeNode u, int tab, BufferedWriter out )
    throws IOException
    {
        String name = null;
        String text = null;
        for ( int i = 0; i < tab; i++ )
            out.write ( " " );
        name = "<"+u.toString() + " ";
        
        PropertyTable props = (PropertyTable)u.getUserObject();
        if ( props.getSize() > 1 )
            for ( int i = 1; i < props.getSize(); i++ )
                if ( !props.getPropertyNameAt(i).equals("TEXT") )
                    name = name.concat(props.getPropertyNameAt(i)
                        + "=\""+ props.getPropertyValueAt(i) + "\" ");
                else
                    text = props.getPropertyValueAt(i);
        name = name.concat(">\n");
        out.write(name);
        
        if ( text != null )
        {
            for ( int i = 0; i < tab; i++ )
                out.write ( " " );
            out.write ( text + "\n" );
        }
        
        for ( int i = 0; i < u.getChildCount(); i++ )
            saver ( (DefaultMutableTreeNode)u.getChildAt(i), tab + 2, out );
        for ( int i = 0; i < tab; i++ )
            out.write ( " " );
        out.write("</"+u.toString()+">\n");
    }
    
    /**
     * Loading tree from file
     * @param fileName name of opening file
     * @return tree from file
     */
    public DefaultMutableTreeNode loadFromFile ( String fileName )
    throws IOException
    {
        curUnit = new DefaultMutableTreeNode( "root" );
        try 
        {
            BufferedReader binp =
                 new BufferedReader(
                   new FileReader(fileName));
            InputSource inp = new InputSource ();
            inp.setCharacterStream(binp);
         SAXParserFactory factory = SAXParserFactory.newInstance();
         factory.setNamespaceAware(true);
         SAXParser parser = factory.newSAXParser();
         XMLReader reader = parser.getXMLReader();
         
         reader.setContentHandler(this);
         reader.parse(inp);
        } 
        catch (FactoryConfigurationError e) 
        {
         System.out.println ( "FactoryConfigurationError" );
         System.exit(1);
        } 
        catch (ParserConfigurationException e) 
        {
            System.out.println ( "ParserConfigurationException" );
            System.exit(1);
        }
        catch (SAXException e) 
        {
            System.out.println ( "SAXException" );
            System.exit(1);
        }
        System.out.println ("DEBUG: Document was loaded successfuly");
        return curUnit;
    }
}


Я начал работать с XML недавно и меня интересует, как можно пропарсить DTD-шку. Смотрел в оффициальных докак - не нашел. Может кто-нибудь скажет сражу какой код и куда надо добавить? Заранее благодарен smile
PM Jabber   Вверх
LSD
Дата 10.12.2006, 13:04 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15718
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



Ты хочешь именно парсить DTD, или организовать проверку XML документа по DTD?


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
Goganchic
Дата 11.12.2006, 14:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 678
Регистрация: 18.6.2004

Репутация: нет
Всего: 5



Именно парсить. Я делаю XML редактор и мне надо сделать юзеру что-то вроде комбо-бокса, из которого он будет выбирать, что можно добавить, а также чтобы некоторые обязательные поля добавлялись самостоятельно.
PM Jabber   Вверх
Goganchic
Дата 20.12.2006, 10:59 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 678
Регистрация: 18.6.2004

Репутация: нет
Всего: 5



Как я понял - стандартного парсера DTD нет, поэтому приходится делать свой.
PM Jabber   Вверх
LSD
Дата 20.12.2006, 12:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15718
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



Средства то есть, например у того же Xerces-а:
Код
import org.apache.xerces.impl.dtd.DTDGrammar;
import org.apache.xerces.impl.dtd.XMLDTDLoader;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.parser.XMLInputSource;

import java.io.FileInputStream;

public class DTDParse
{
  public static void main(String[] args) throws Exception
  {
    SymbolTable symbolTable = new SymbolTable();
    XMLDTDLoader loader = new XMLDTDLoader(symbolTable);
    DTDGrammar dtdGrammar = (DTDGrammar) loader.loadGrammar(new XMLInputSource("", "", "", new FileInputStream("log4j.dtd"), "UTF-8"));
  }
}

Или как вариант использовать NekoDTD, для конвертации DTD в XML.


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.1086 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.