M
M
Maxim2020-08-12 15:51:48
Python
Maxim, 2020-08-12 15:51:48

parsing xml. How to get around the problem with one position in the document?

I am learning python, in terms of parsing xml and entering data into the database.
for parsing, I use the xmltodict library, because it parses the file and provides it as a dictionary.

there is an xml of the form
<wb:Content>
  <wb:Position>
    <wb:Identity>1</wb:Identity>
    <wb:Product>
      <pref:Type>АП</pref:Type>
      <pref:FullName>Название</pref:FullName>
      <pref:AlcCode>0323103000001227178</pref:AlcCode>
      <pref:Capacity>0.500</pref:Capacity>
      <pref:UnitType>Packed</pref:UnitType>
      <pref:AlcVolume>4.000</pref:AlcVolume>
      <pref:ProductVCode>500</pref:ProductVCode>
      <pref:Producer>  ...      </pref:Producer>
    </wb:Product>
    <wb:Quantity>20.000</wb:Quantity>
    <wb:Price>57.19</wb:Price>
    <wb:Party>Партия №60074</wb:Party>
    <wb:FARegId>000000000000</wb:FARegId>
    <wb:InformF2>  ...  </wb:InformF2>
  </wb:Position>
</wb:Content>

the problem is that there can be multiple wb:Position elements.
taking into account the specifics of the library, if there is only one wb:Position element, then its child elements will be accessed without using a nested list. For example, there is only one position: if there are several then: It is not known how many wb:Position elements will be, if it is sorted in a loop, then you can catch an exception, since key 0 does not exist. How to check the number of wb:Position elements? Or would it be better to use a different parser?
xml['wb:Content']['wb:Position']['wb:Identity']


xml['wb:Content']['wb:Position'][3]['wb:Identity']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alan Gibizov, 2020-08-12
@maxpointn2point

Well, you can stupidly try and if an exception, then one element is nested. It's stupid, but if "on a one-time script" - it will probably go.

P
PavelMos, 2020-08-12
@PavelMos

So make a loop and inline the handling of the possibility of absence

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question