powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / C++ [игнор отключен] [закрыт для гостей] / Разбор XML
18 сообщений из 18, страница 1 из 1
Разбор XML
    #33879453
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Посоветуйте как наиболее просто разобрать XML на Cи в Linux? Лучше всего пример приведите, так как опыта ноль. Например такой файл:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
<book>
  <style>
    <font name="Times New Roman" name="Мой шрифт" />
    <para name="Обычный" />
    <para align="center" name="По центру" />
  </style>
  <document>
    <text parastyle="По центру">Привет</text>
    <text>Это пример файла XML</text>
  </document>
</book>
Нужно прочитать это и записать в файл или лучше в переменные соответствующих типов.
Заранее спасибо.
...
Рейтинг: 0 / 0
Разбор XML
    #33879513
Фотография blinded
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Взять xerces-c и не мучится. Например здесь http://apache.rediska.ru/xml/xerces-c/
...
Рейтинг: 0 / 0
Разбор XML
    #33879587
postt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Нашел пример:
Код: 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.
#include <stdio.h>
#include <libxml/parser.h>
#define CONF "/home/steck/file.xml"

int main(int argc, char *argv[])
{
xmlNodePtr cur;
xmlDocPtr doc;

doc = xmlParseFile(CONF);
  if(doc == NULL)
  {
    fprintf(stderr,"Error parsing file\n");
    return - 1 ;
  }
  cur = xmlDocGetRootElement(doc);
  if(xmlStrcmp(cur->name,(const xmlChar *)"request"))
    return - 1 ;
  cur = cur->xmlChildrenNode;
  while(cur != NULL)
  {
      if((!xmlStrcmp(cur->name,(const xmlChar *)"header")))
            {
                    printf("Section \"header\"\n");
                    printf("action = %s\n",xmlGetProp(cur,"action"));
                    printf("dealer = %s\n",xmlGetProp(cur,"dealer"));
            }
             if((!xmlStrcmp(cur->name,(const xmlChar *)"account")))
        {
                    printf("Section \"account\"\n");
                printf("service = %s\n",xmlGetProp(cur,"service"));
                printf("id = %s\n",xmlGetProp(cur,"id"));
                printf("id2 = %s\n",xmlGetProp(cur,"id2"));
                printf("id3 = %s\n",xmlGetProp(cur,"id3"));
                printf("id4 = %s\n",xmlGetProp(cur,"id4"));
                        
        }
                if((!xmlStrcmp(cur->name,(const xmlChar *)"operation")))
                {
                    printf("Section \"Operation\"\n");

                    printf("id = %s\n",xmlGetProp(cur,"id"));
                    printf("sum = %s\n",xmlGetProp(cur,"sum"));
                    printf("point = %s\n",xmlGetProp(cur,"point"));
                    printf("check = %s\n",xmlGetProp(cur,"check"));
                }
                cur = cur->next;
    }
    }
Код: plaintext
1.
2.
3.
4.
<request>
<header action=”payment” dealer=”mCash”/>
<account service=” 0 ” id=”Иванов Иван” id2=” 123456879 ” id3=”” id4=”” />
<operation id=” 7456646 ” sum=” 9 . 45 ” point=” 350 ” check=” 17235 ”/>
</request>

Но он не компилируется. Выдает:
/usr/include/libxml2/libxml/parser.h:15:31: libxml/xmlversion.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:16:25: libxml/tree.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:17:25: libxml/dict.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:18:25: libxml/hash.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:19:26: libxml/valid.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:20:29: libxml/entities.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:21:29: libxml/xmlerror.h: No such file or directory
/usr/include/libxml2/libxml/parser.h:22:30: libxml/xmlstring.h: No such file or directory
In file included from xml.cpp:3:

итд. Пробовал #include <libxml/parser.h> заменять на cat /usr/include/libxml2/libxml/.
Код: plaintext
1.
2.
3.
4.
5.
6.
ls
DOCBparser.h  catalog.h   globals.h   parserInternals.h   tree.h      xmlautomata.h  xmlregexp.h        xmlversion.h
HTMLparser.h  chvalid.h   hash.h      pattern.h           uri.h       xmlerror.h     xmlsave.h          xmlwriter.h
HTMLtree.h    debugXML.h  list.h      relaxng.h           valid.h     xmlexports.h   xmlschemas.h       xpath.h
SAX.h         dict.h      nanoftp.h   schemasInternals.h  xinclude.h  xmlmemory.h    xmlschemastypes.h  xpathInternals.h
SAX2.h        encoding.h  nanohttp.h  schematron.h        xlink.h     xmlmodule.h    xmlstring.h        xpointer.h
c14n.h        entities.h  parser.h    threads.h           xmlIO.h     xmlreader.h    xmlunicode.h


Установил libxml2,libxml2-devel. Чего не хватает???
...
Рейтинг: 0 / 0
Разбор XML
    #33879934
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Разобрался в makefile.
Теперь выдает:
Код: 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.
xml.cpp: 26 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 26 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp:27: error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp:27: error:   initializing argument 2 of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 32 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 32 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp:33: error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp:33: error:   initializing argument 2 of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 34 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 34 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp:35: error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp:35: error:   initializing argument 2 of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 36 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 36 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp:42: error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp:42: error:   initializing argument 2 of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 43 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 43 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp:44: error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp:44: error:   initializing argument 2 of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 45 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 45 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'
xml.cpp: 49 : 4 : warning: no newline at end of file
make: *** [default] Error  1 
...
Рейтинг: 0 / 0
Разбор XML
    #33879947
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Помогите найти ошибки. Если закомментить те строки,то выдает:
Код: plaintext
1.
2.
3.
4.
5.
6.
make
g++ -g -mpentium -I/usr/include/libxml2 -L/usr/local/pgsql/lib -lpq -L/usr/lib -lstdc++  xml.cpp -o  xml
xml.cpp: 51 : 3 : warning: no newline at end of file
/usr/bin/ld: cannot find -lpq
collect2: ld returned  1  exit status
make: *** [default] Error  1 
...
Рейтинг: 0 / 0
Разбор XML
    #33880000
maXmo
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
в конце файла добавь новую строку.
...
Рейтинг: 0 / 0
Разбор XML
    #33880011
Akh
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
htttПомогите найти ошибки. Если закомментить те строки,то выдает:
Код: plaintext
1.
2.
3.
4.
5.
6.
make
g++ -g -mpentium -I/usr/include/libxml2 -L/usr/local/pgsql/lib -lpq -L/usr/lib -lstdc++  xml.cpp -o  xml
xml.cpp: 51 : 3 : warning: no newline at end of file
/usr/bin/ld: cannot find -l[color=red]pq[/color]
collect2: ld returned  1  exit status
make: *** [default] Error  1 


Не находит какую-то библиотеку libpq...
...
Рейтинг: 0 / 0
Разбор XML
    #33880027
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
maXmoв конце файла добавь новую строку.
Какую, не совсем понял? Ошибка на этапе компилляции проявляется, а не во время работы...
...
Рейтинг: 0 / 0
Разбор XML
    #33880028
maXmo
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
кстати, xmlChar, поди, объявлен как wchar_t?
...
Рейтинг: 0 / 0
Разбор XML
    #33880104
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: plaintext
1.
2.
3.
4.
5.
6.
 cat Makefile
CC=g++ -g -mpentium
INC=-I/usr/include/libxml2
LIBS=-L/usr/local/pgsql/lib -lpq -L/usr/lib -lstdc++

default : xml.cpp
    ${CC} ${INC} ${LIBS}  xml.cpp -o  xml
.
Думаю тут может быть ошибка.
...
Рейтинг: 0 / 0
Разбор XML
    #33880114
Akh
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
httt
Код: plaintext
-lpq
.
Думаю тут может быть ошибка.
...
Рейтинг: 0 / 0
Разбор XML
    #33880120
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Без -lpq:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
 make
g++ -g -mpentium -I/usr/include/libxml2  -L/usr/local/pgsql/lib -L/usr/lib -lstdc++  xml.cpp -o  xml
xml.cpp: 52 : 3 : warning: no newline at end of file
/tmp/.private/root/ccc518rG.o(.text+0x25): In function `main':
/PROJECT/xml.cpp:11: undefined reference to `xmlParseFile'
/tmp/.private/root/ccc518rG.o(.text+0x5e):/PROJECT/xml.cpp: 17 : undefined reference to `xmlDocGetRootElement'
/tmp/.private/root/ccc518rG.o(.text+0x77):/PROJECT/xml.cpp:18: undefined reference to `xmlStrcmp'
/tmp/.private/root/ccc518rG.o(.text+0xb0):/PROJECT/xml.cpp: 23 : undefined reference to `xmlStrcmp'
/tmp/.private/root/ccc518rG.o(.text+0xda):/PROJECT/xml.cpp:29: undefined reference to `xmlStrcmp'
/tmp/.private/root/ccc518rG.o(.text+0x104):/PROJECT/xml.cpp: 38 : undefined reference to `xmlStrcmp'
collect2: ld returned  1  exit status
make: *** [default] Error  1 
...
Рейтинг: 0 / 0
Разбор XML
    #33880148
Akh
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
htttБез -lpq:

Разберись, что за библотека, установи.
...
Рейтинг: 0 / 0
Разбор XML
    #33880160
Akh
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторПервоначально использовался Postgresql-6.1 с интерфейсом, основанным на библиотеке libpq.1
...
Рейтинг: 0 / 0
Разбор XML
    #33880260
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Makefile использовался вообще говоря изначально не для компиляции этой проги... Может кто поделится опытом..очень надо? Или даст другой рабочий пример.
...
Рейтинг: 0 / 0
Разбор XML
    #33880296
Akh
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
htttMakefile использовался вообще говоря изначально не для компиляции этой проги... Может кто поделится опытом..очень надо? Или даст другой рабочий пример.

Попробуй добавить -lxml или -lxml2
...
Рейтинг: 0 / 0
Разбор XML
    #33880617
White Owl
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
htttРазобрался в makefile.
Теперь выдает:
Код: plaintext
1.
xml.cpp: 26 : error: invalid conversion from `const char*' to `const xmlChar*'
xml.cpp: 26 : error:   initializing argument  2  of `xmlChar* xmlGetProp(xmlNode*, const xmlChar*)'

Замени:
Код: plaintext
1.
2.
 printf("service = %s\n",xmlGetProp(cur,"service"));
на 
 printf("service = %s\n",xmlGetProp(cur, (const xmlChar*)"service"));
и так все строки работающие с xml* функциями.
...
Рейтинг: 0 / 0
Разбор XML
    #33881039
httt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Всем большое спасибо. Почти все работает. Дальше буду разбираться.:)
...
Рейтинг: 0 / 0
18 сообщений из 18, страница 1 из 1
Форумы / C++ [игнор отключен] [закрыт для гостей] / Разбор XML
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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