H
H
hawkkoff2014-04-13 18:15:41
Python
hawkkoff, 2014-04-13 18:15:41

Can't parse xml with lxml python?

Good afternoon. I can not generate the required dictionary
, there is xml

<one val='value1'>
  <text> text1 </text>
  <two>
    <text> text two 1</text>
  </two>
  <two>
    <text> text two 2</text>
  </two>
  <two>
    <text> text two 3</text>
  </two>
</one>
<one val='value2'>
  <text> text2 </text>
  <two>
    <text> text two 4</text>
  </two>
  <two>
    <text> text two 5</text>
  </two>
</one>
<one val='value3'>
  <text> text3 </text>
  <two>
    <text> text two 6</text>
  </two>
</one>

I want to get
[{'one':'text1','val':'value1', 'two': ['text two 1','text two 2','text two 3']},
{'one ':'text2','val':'value2', 'two': ['text two 4','text two 5']}
{'one':'text3','val':'value3', ' two': ['text two 6']}
]
I have no idea how to do this with lxml . I tried xpath, but nothing came out sane, I could only make arrays ['text1','text2','text3'] and ['text two 1','text two 2','text two 3','text two 4','text two 5','text two 6'] , but I realized that the structure is needed. Thanks in advance

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2014-04-13
@seriyPS

You don't need XPath. lxml.de/tutorial.html#elements-are-lists
Do iterate over elements and recursive function (or just nested loops).
What's bad is that your XML structure ambiguously matches the structure of python dictionaries. Well, the given XML is invalid - there is no root element (or is it incomplete?).

def to_dicts(element):
  obj = {'tag': element.tag,
        'attrs': element.attrs,
        'childs': [to_dicts(child) for child in element]}
  return obj

[
[email protected], 2014-09-29
@gaenar

SeriyPS, are ready to offer you a job on the topic of Parsing. The project is large, interesting and long-term, socially oriented and with good karma. First by piecework, then by agreement. We are ready to invest 200K or more in the topic.
Can you share contacts for communication?

X
xmoonlight, 2015-09-13
@ruslite

telnet (ip где лежит БД) 3306
Is there a connection?

S
sivabur, 2015-09-13
@sivabur

1. Check ping to this ip
2. connect first with the help of any client (graphical or from the command line through the standard mysql client)
If everything is ok. Then google how exactly with the help to connect to the database.
If not ok, then the database server is not running. Or incorrect connection data. No driver is needed on the server. Except for the server itself and permissions to connect to it from any IP.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question