Как собрать текстовые узлы на одном уровне элемента? - PullRequest
0 голосов
/ 22 мая 2018

ниже пример xml.Я изучаю модуль xml.etree.ElementTree, а не lxml.

<data>
    <AAA>
        <CCC>
            <BBB>This</BBB>
        </CCC>
        <CCC>  
            <BBB>is</BBB>
        </CCC>
        <CCC>
            <BBB>test1</BBB>
        </CCC>
    </AAA>

    <AAA>
        <CCC>
            <BBB>This is test</BBB>
        </CCC>
    </AAA>

   <AAA>
        <CCC>
            <BBB>222222</BBB>
        </CCC>
        <CCC>
            <BBB>333333</BBB>
        </CCC>      
    </AAA>  

    <AAA>
        <BBB>
            <CCC>This is test</CCC>
        </BBB>
    </AAA>
</data>

Я пытаюсь собрать все тексты BBB под CCC в рамках элемента AAA.но я понятия не имею, почему это не работает.при запуске ошибки нет, но тексты не собираются.Интересно, почему этот код не работает?

BBB_collect = ''.join(BBB.itertext())

, пожалуйста, проверьте ниже

import xml.etree.ElementTree as ET
import re

f1 = open ("C:\\test\\Data.xml","r",encoding="utf=8")
f2 = open ("C:\\test\\output.xml","wt",encoding="utf=8")
doc = ET.parse("C:\\test\\Data.xml")
root = doc.getroot()
a = 0

try:
    while True :
        AAA = root.findall('AAA')[a]
        for CCC in AAA.findall('CCC'):
            for BBB in CCC.findall('BBB'):
                BBB_collect = ''.join(BBB.itertext())
                print(BBB_collect)
        print('===============')
        a = a+1
except IndexError :
    pass

Не могли бы вы дать Ма какой-нибудь совет?Что с ним не так?

В конечном счете, это моя цель ниже.

<data>
    <AAA>
        <CCC>
            <BBB>Thisistest1</BBB>
        </CCC>
    </AAA>

    <AAA>
        <CCC>
            <BBB>This is test</BBB>
        </CCC>
    </AAA>

    <AAA>
        <CCC>
            <BBB>222222333333</BBB>
        </CCC>
    </AAA>  

    <AAA>
        <BBB>
            <CCC>This is test</CCC>
        </BBB>
    </AAA>
</data>

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Это может помочь.

Демонстрация:

import xml.etree.ElementTree as ET
doc = ET.fromstring(data)   

for AAA in doc.findall('AAA'):
    bText = ""
    for CCC in AAA.findall('CCC'):
        for BBB in CCC.findall('BBB'):
            bText += BBB.text
    print(bText)

Вывод:

Thisistest1
This is test
222222333333
This is test
0 голосов
/ 22 мая 2018

Это работает?

try:
    while True :
        AAA = root.findall('AAA')[a]
        BBB_text = ""
        for CCC in AAA.findall('CCC'):
            for BBB in CCC.findall('BBB'):
                BBB_text = BBB_text+BBB.text
        print(BBB_text)
        print('===============')
        a = a+1
except IndexError :
    pass
...