පයිතන් හි XML විග්‍රහ කරන්නේ කෙසේද?


1030

මට එක්ස්එම්එල් අඩංගු දත්ත සමුදායක පේළි රාශියක් ඇති අතර විශේෂිත නෝඩ් ගුණාංගයක අවස්ථා ගණනය කිරීම සඳහා මම පයිතන් පිටපතක් ලිවීමට උත්සාහ කරමි.

මගේ ගස පෙනේ:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

පයිතන් භාවිතයෙන් "1"සහ "2"XML හි ඇති ගුණාංග වෙත ප්‍රවේශ වන්නේ කෙසේද ?


Answers:


804

මම යෝජනා කරනවා ElementTree. එකම ඒපීඅයි හි වෙනත් අනුකූල ක්‍රියාත්මක කිරීම් තිබේ lxml, සහ cElementTreeපයිතන් සම්මත පුස්තකාලයේම; නමුත්, මෙම සන්දර්භය තුළ, ඔවුන් ප්‍රධාන වශයෙන් එකතු කරන දෙය ඊටත් වඩා වේගවත් වේ - ක්‍රමලේඛන කොටසේ පහසුව රඳා පවතින්නේ එය ElementTreeනිර්වචනය කරන API මත ය .

පළමුව rootXML වෙතින් මූලද්‍රව්‍ය නිදසුනක් සාදන්න , උදා: XML ශ්‍රිතය සමඟ, හෝ ගොනුවක් විග්‍රහ කිරීමෙන්:

import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()

හෝ පෙන්වා ඇති වෙනත් බොහෝ ක්‍රම වලින් එකක් ElementTree. ඉන්පසු එවැනි දෙයක් කරන්න:

for type_tag in root.findall('bar/type'):
    value = type_tag.get('foobar')
    print(value)

ඒ හා සමාන, සාමාන්‍යයෙන් තරමක් සරල, කේත රටා.


41
පයිතන් සමඟ එන xml.etree.cElementTree ඔබ නොසලකා හරින බවක් පෙනේ. සමහර අංශවල තම් lxml වේගවත් වේ ("lxml හි iterparse () cET හි ඇති ඒවාට වඩා තරමක් මන්දගාමී වේ" - lxml කතෘගේ විද්‍යුත් තැපෑල).
ජෝන් මචින්

7
ElementTree ක්‍රියා කරන අතර එය පයිතන් සමඟ ඇතුළත් වේ. සීමිත XPath සහය ඇතත් ඔබට මූලද්‍රව්‍යයක මවුපියන් වෙත ගමන් කළ නොහැක, එමඟින් සංවර්ධනය මන්දගාමී විය හැකිය (විශේෂයෙන් ඔබ මෙය නොදන්නේ නම්). විස්තර සඳහා මවුපියන් ලබා ගැනීම සඳහා python xml විමසුම බලන්න.
සැමුවෙල්

11
lxmlවේගයට වඩා එකතු කරයි. එය අවස්ථා කිහිපයකදී ඉතා ප්‍රයෝජනවත් විය හැකි මව් නෝඩ්, එක්ස්එම්එල් ප්‍රභවයේ රේඛා අංකය වැනි තොරතුරු වලට පහසුවෙන් ප්‍රවේශ විය හැකිය.
සහීල් ගොඩ්හාන්

13
ElementTree හි සමහර අවදානම් ගැටළු ඇති බව පෙනේ, මෙය Warning The xml.etree.ElementTree module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.
ලියකියවිලි

6
Rist ක්‍රිස්ටික් බොහෝ xml විග්‍රහකයන්ගේ තත්වය මෙය බව පෙනේ, XML අවදානම් පිටුව බලන්න .
gitaarik

432

minidom වේගවත්ම හා ලස්සන කෙළින්ම ඉදිරියට.

XML:

<data>
    <items>
        <item name="item1"></item>
        <item name="item2"></item>
        <item name="item3"></item>
        <item name="item4"></item>
    </items>
</data>

පයිතන්:

from xml.dom import minidom
xmldoc = minidom.parse('items.xml')
itemlist = xmldoc.getElementsByTagName('item')
print(len(itemlist))
print(itemlist[0].attributes['name'].value)
for s in itemlist:
    print(s.attributes['name'].value)

ප්‍රතිදානය:

4
item1
item1
item2
item3
item4

9
"අයිතමය 1" හි වටිනාකම ඔබ ලබා ගන්නේ කෙසේද? උදාහරණයක් ලෙස: <item name = "item1"> අගය 1 </item>
swmcdonnell

ලියකියවිලි කොහේද minidom? මට මෙය හමු වූ නමුත් එය සිදු නොවේ: docs.python.org/2/library/xml.dom.minidom.html
උභයජීවී

1
itemලේඛනයේ ඉහළ මට්ටමේ සිට එය කෙලින්ම සොයා ගන්නේ මන්දැයි මම ව්‍යාකූල වී සිටිමි. ඔබ එය ( data->items) මාර්ගය සැපයුවහොත් එය පිරිසිදු නොවේද? මක්නිසාද යත්, ඔබ data->secondSetOfItemsසතුව නෝඩ් නම් කර ඇති itemඅතර ඔබට කට්ටල දෙකෙන් එකක් පමණක් ලැයිස්තු ගත කිරීමට අවශ්‍ය නම් itemකුමක් කළ යුතුද?
උභයජීවී


ඔබට වරහන ඉවත් කිරීමට අවශ්‍ය වාක්‍ය ඛණ්ඩය මෙහි ක්‍රියා නොකරනු ඇත for s in itemlist: print(s.attributes['name'].value)
ඇලෙක්ස් බෝර්සෝඩි

241

ඔබට BeautifulSoup භාවිතා කළ හැකිය :

from bs4 import BeautifulSoup

x="""<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>"""

y=BeautifulSoup(x)
>>> y.foo.bar.type["foobar"]
u'1'

>>> y.foo.bar.findAll("type")
[<type foobar="1"></type>, <type foobar="2"></type>]

>>> y.foo.bar.findAll("type")[0]["foobar"]
u'1'
>>> y.foo.bar.findAll("type")[1]["foobar"]
u'2'

තොරතුරු සඳහා ස්තූතියි @ibz, ඔව්, ඇත්ත වශයෙන්ම, ප්‍රභවය නිසි ලෙස සකසා නොමැති නම්, විග්‍රහ කරන්නන් සඳහා ද විග්‍රහ කිරීම දුෂ්කර වනු ඇත.
ඔබ

46
අවුරුදු තුනකට පසු bs4 සමඟ මෙය ඉතා හොඳ විසඳුමක්, ඉතා නම්‍යශීලී, විශේෂයෙන් ප්‍රභවය නිසි ලෙස සකසා නොමැති නම්
cedbeu

8
@YOU BeautifulStoneSoupක්ෂය වේ. භාවිතා කරන්නBeautifulSoup(source_xml, features="xml")
andilabs

5
තවත් වසර 3 කට පසුව, මම එක්ස්එම්එල් භාවිතයෙන් පැටවීමට උත්සාහ කළෙමි ElementTree, අවාසනාවකට මම ස්ථානවල මූලාශ්‍රය සකස් කර BeautifulSoupකිසිදු වෙනසක් නොමැතිව එකවරම වැඩ කළොත් මිස එය විග්‍රහ කළ නොහැක .
ViKiG

8
@andi ඔබ අදහස් කළේ "අතහැර දැමූ" යන්නයි. “අවප්‍රමාණය” යන්නෙන් අදහස් වන්නේ එය සාමාන්‍යයෙන් වයස හෝ ඇඳුම් පැළඳුම් හා සාමාන්‍ය භාවිතයෙන් ඉරී යාම නිසා එහි වටිනාකම අඩුවීමයි.
jpmc26

100

එහි බොහෝ විකල්ප තිබේ. වේගය සහ මතක භාවිතය ගැටළුවක් නම් cElementTree විශිෂ්ටයි. ගොනුව භාවිතයෙන් සරලව කියවීමට සාපේක්ෂව එයට ඉහළින් ඇත්තේ ඉතා අල්ප ප්‍රමාණයකි readlines.

අදාළ ප්‍රමිතික පහත වගුවේ සොයාගත හැකිය, එය cElementTree වෙබ් අඩවියෙන් පිටපත් කර ඇත :

library                         time    space
xml.dom.minidom (Python 2.1)    6.3 s   80000K
gnosis.objectify                2.0 s   22000k
xml.dom.minidom (Python 2.4)    1.4 s   53000k
ElementTree 1.2                 1.6 s   14500k  
ElementTree 1.2.4/1.3           1.1 s   14500k  
cDomlette (C extension)         0.540 s 20500k
PyRXPU (C extension)            0.175 s 10850k
libxml2 (C extension)           0.098 s 16000k
readlines (read as utf-8)       0.093 s 8850k
cElementTree (C extension)  --> 0.047 s 4900K <--
readlines (read as ascii)       0.032 s 5050k   

@Jfs පෙන්වා දුන් පරිදි , cElementTreeපයිතන් සමඟ එකතු වේ:

  • Python මීට උදාහරණ 2: from xml.etree import cElementTree as ElementTree.
  • පයිතන් 3: from xml.etree import ElementTree(වේගවත් සී අනුවාදය ස්වයංක්‍රීයව භාවිතා වේ).

9
CElementTree භාවිතා කිරීමේ අවාසි තිබේද? එය මොළයක් නැති බව පෙනේ.
mayhewsw

6
පෙනෙන විදිහට ඔවුන්ට OS X හි පුස්තකාලය භාවිතා කිරීමට අවශ්‍ය නැත. මන්දයත් මම විනාඩි 15 කට වඩා වැඩි කාලයක් ගත කර ඇති අතර එය බාගත කරගත යුත්තේ කොතැනින්දැයි සොයා ගැනීමට උත්සාහ කරන අතර කිසිදු සබැඳියක් ක්‍රියා නොකරයි. ලියකියවිලි නොමැතිකම හොඳ ව්‍යාපෘති සාර්ථක වීම වලක්වනු ඇත.
ඇදගන්නාසුළු

8
@ ස්ටනර්: එය stdlib හි ඇත, එනම් ඔබට කිසිවක් බාගත කිරීමට අවශ්‍ය නැත. Python 2: from xml.etree import cElementTree as ElementTree. පයිතන් 3 හි: from xml.etree import ElementTree(වේගවත් සී අනුවාදය ස්වයංක්‍රීයව භාවිතා වේ)
jfs

1
aymayhewsw ElementTreeකිසියම් කාර්යයක් සඳහා කාර්යක්ෂමව භාවිතා කරන්නේ කෙසේදැයි සොයා ගැනීමට වැඩි උත්සාහයක් දරයි . මතකයට ගැලපෙන ලේඛන සඳහා, එය භාවිතා කිරීම පහසුය minidom, කුඩා XML ලේඛන සඳහා එය හොඳින් ක්‍රියා කරයි.
Acumenus

45

සරල බව සඳහා xmltodict යෝජනා කරමි .

එය ඔබගේ XML එක ඇණවුම් කළ නියෝගයකට විග්‍රහ කරයි;

>>> e = '<foo>
             <bar>
                 <type foobar="1"/>
                 <type foobar="2"/>
             </bar>
        </foo> '

>>> import xmltodict
>>> result = xmltodict.parse(e)
>>> result

OrderedDict([(u'foo', OrderedDict([(u'bar', OrderedDict([(u'type', [OrderedDict([(u'@foobar', u'1')]), OrderedDict([(u'@foobar', u'2')])])]))]))])

>>> result['foo']

OrderedDict([(u'bar', OrderedDict([(u'type', [OrderedDict([(u'@foobar', u'1')]), OrderedDict([(u'@foobar', u'2')])])]))])

>>> result['foo']['bar']

OrderedDict([(u'type', [OrderedDict([(u'@foobar', u'1')]), OrderedDict([(u'@foobar', u'2')])])])

3
එකඟ විය. ඔබට XPath හෝ සංකීර්ණ කිසිවක් අවශ්‍ය නොවේ නම්, මෙය භාවිතා කිරීම වඩා සරල ය (විශේෂයෙන් පරිවර්තකයා තුළ); JSON වෙනුවට XML ප්‍රකාශයට පත් කරන REST API සඳහා පහසුය
ඩෑන් පැසාරෝ

4
OrdersDict අනුපිටපත් යතුරු සඳහා සහය නොදක්වන බව මතක තබා ගන්න. බොහෝ එක්ස්එම්එල් එකම වර්ගයේ සහෝදර සහෝදරියන්ගෙන් පිරී ඇත (කියන්න, කොටසක ඇති සියලුම ඡේද, හෝ ඔබේ තීරුවේ ඇති සියලුම වර්ග). එබැවින් මෙය ක්‍රියාත්මක වන්නේ ඉතා සීමිත විශේෂ අවස්ථා සඳහා පමණි.
TextGeek

2
TeTextGeek මේ අවස්ථාවේ දී, result["foo"]["bar"]["type"]සියලු <type>මූලද්‍රව්‍යයන්ගේ ලැයිස්තුවක් වන බැවින් එය තවමත් ක්‍රියාත්මක වේ (ව්‍යුහය ටිකක් අනපේක්ෂිත වුවත්).
luator

38

lxml.objectify ඇත්තෙන්ම සරලයි.

ඔබේ නියැදි පෙළ ගැනීම:

from lxml import objectify
from collections import defaultdict

count = defaultdict(int)

root = objectify.fromstring(text)

for item in root.bar.type:
    count[item.attrib.get("foobar")] += 1

print dict(count)

ප්‍රතිදානය:

{'1': 1, '2': 1}

countපෙරනිමි යතුරු සහිත ශබ්දකෝෂයක එක් එක් අයිතමයේ ගණන් ගබඩා කරයි, එබැවින් ඔබට සාමාජිකත්වය පරීක්ෂා කිරීමට අවශ්‍ය නැත. ඔබට බැලීමට උත්සාහ කළ හැකිය collections.Counter.
රයන් ජින්ස්ට්‍රෝම්

20

පයිතන් එක්ස්පෝට් එක්ස්එම්එල් විග්‍රහයට අතුරු මුහුණතක් ඇත.

xml.parsers.expat

එය වලංගු නොවන විග්‍රහයකි, එබැවින් නරක XML හසු නොවනු ඇත. නමුත් ඔබේ ගොනුව නිවැරදි බව ඔබ දන්නේ නම්, මෙය ඉතා හොඳයි, ඔබට අවශ්‍ය තොරතුරු ඔබට ලැබෙනු ඇති අතර ඉතිරි සියල්ල මැස්සෙන් ඉවත දැමිය හැකිය.

stringofxml = """<foo>
    <bar>
        <type arg="value" />
        <type arg="value" />
        <type arg="value" />
    </bar>
    <bar>
        <type arg="value" />
    </bar>
</foo>"""
count = 0
def start(name, attr):
    global count
    if name == 'type':
        count += 1

p = expat.ParserCreate()
p.StartElementHandler = start
p.Parse(stringofxml)

print count # prints 4

+1 මක්නිසාද යත්, වලංගු නොවන මූලාශ්‍ර අක්ෂර සමඟ ක්‍රියා කරන වලංගු නොවන විග්‍රහයක් මම සොයමි. මෙය මට අවශ්‍ය ප්‍රති results ල ලබා දෙනු ඇතැයි බලාපොරොත්තු වෙමි.
නේතන් සී. ට්‍රෙෂ්

14

මම යෝජනා කරනවා declxml .

සම්පුර්ණ අනාවරණය කිරීම: මම මෙම පුස්තකාලය ලිව්වේ ElementTree සමඟ අත්‍යවශ්‍ය විග්‍රහ / අනුක්‍රමික කේත පේළි දුසිම් ගණනක් ලිවීමට අවශ්‍ය නොවී XML සහ පයිතන් දත්ත ව්‍යුහයන් අතර පරිවර්තනය වීමට ක්‍රමයක් සොයන බැවිනි.

Declxml සමඟ, ඔබ ඔබේ XML ලේඛනයේ ව්‍යුහය සහ XML සහ Python දත්ත ව්‍යුහයන් අතර සිතියම් ගත කරන්නේ කෙසේද යන්න ප්‍රකාශ කිරීමට අර්ථකථනය කිරීමට සකසනයන් භාවිතා කරයි . ප්‍රොසෙසර භාවිතා කරනුයේ අනුක්‍රමිකකරණය සහ විග්‍රහ කිරීම මෙන්ම මූලික මට්ටමේ වලංගු භාවයක් සඳහා ය.

පයිතන් දත්ත ව්‍යුහයන්ට විග්‍රහ කිරීම සරල ය:

import declxml as xml

xml_string = """
<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>
"""

processor = xml.dictionary('foo', [
    xml.dictionary('bar', [
        xml.array(xml.integer('type', attribute='foobar'))
    ])
])

xml.parse_from_string(processor, xml_string)

ප්‍රතිදානය නිපදවන:

{'bar': {'foobar': [1, 2]}}

XML වෙත දත්ත අනුක්‍රමික කිරීම සඳහා ඔබට එකම ප්‍රොසෙසරයක් භාවිතා කළ හැකිය

data = {'bar': {
    'foobar': [7, 3, 21, 16, 11]
}}

xml.serialize_to_string(processor, data, indent='    ')

එය පහත ප්‍රතිදානය නිපදවයි

<?xml version="1.0" ?>
<foo>
    <bar>
        <type foobar="7"/>
        <type foobar="3"/>
        <type foobar="21"/>
        <type foobar="16"/>
        <type foobar="11"/>
    </bar>
</foo>

ඔබට ශබ්ද කෝෂ වෙනුවට වස්තූන් සමඟ වැඩ කිරීමට අවශ්‍ය නම්, වස්තූන් වෙත සහ ඉන් පිටත දත්ත පරිවර්තනය කිරීම සඳහා ඔබට සකසනයන් අර්ථ දැක්විය හැකිය.

import declxml as xml

class Bar:

    def __init__(self):
        self.foobars = []

    def __repr__(self):
        return 'Bar(foobars={})'.format(self.foobars)


xml_string = """
<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>
"""

processor = xml.dictionary('foo', [
    xml.user_object('bar', Bar, [
        xml.array(xml.integer('type', attribute='foobar'), alias='foobars')
    ])
])

xml.parse_from_string(processor, xml_string)

එය පහත ප්‍රතිදානය නිපදවයි

{'bar': Bar(foobars=[1, 2])}

13

තවත් හැකියාවක් එක් කිරීම සඳහා, ඔබට සරල xml-to-python-object පුස්තකාලයක් වන බැවින් , ඔබට untangle භාවිතා කළ හැකිය . මෙන්න ඔබට උදාහරණයක් තිබේ:

ස්ථාපනය:

pip install untangle

භාවිතය:

ඔබගේ XML ගොනුව (ටිකක් වෙනස් කර ඇත):

<foo>
   <bar name="bar_name">
      <type foobar="1"/>
   </bar>
</foo>

සමඟ ලක්ෂණ වෙත ප්‍රවේශ වීම untangle:

import untangle

obj = untangle.parse('/path_to_xml_file/file.xml')

print obj.foo.bar['name']
print obj.foo.bar.type['foobar']

ප්‍රතිදානය වනුයේ:

bar_name
1

Untangle පිළිබඳ වැඩි විස්තර " untangle " හි සොයාගත හැකිය .

එසේම, ඔබ කුතුහලයෙන් සිටී නම්, ඔබට " පයිතන් සහ එක්ස්එම්එල් " හි එක්ස්එම්එල් සහ පයිතන් සමඟ වැඩ කිරීම සඳහා මෙවලම් ලැයිස්තුවක් සොයාගත හැකිය . පෙර පිළිතුරු මගින් වඩාත් සුලභ ඒවා සඳහන් කර ඇති බව ඔබට පෙනෙනු ඇත.


නොගැලපීම මිනිඩොම් වලට වඩා වෙනස් වන්නේ කුමක් ද?
ආරොන් මෑන්

මම මිනිඩොම් සමඟ වැඩ කර නැති නිසා ඒ දෙක අතර වෙනස මට කියන්න බැහැ.
jchanger

10

මෙන්න ඉතා සරල නමුත් effective ලදායී කේතයක් භාවිතා කිරීම cElementTree.

try:
    import cElementTree as ET
except ImportError:
  try:
    # Python 2.5 need to import a different module
    import xml.etree.cElementTree as ET
  except ImportError:
    exit_err("Failed to import cElementTree from any known place")      

def find_in_tree(tree, node):
    found = tree.find(node)
    if found == None:
        print "No %s in file" % node
        found = []
    return found  

# Parse a xml file (specify the path)
def_file = "xml_file_name.xml"
try:
    dom = ET.parse(open(def_file, "r"))
    root = dom.getroot()
except:
    exit_err("Unable to open and parse input definition file: " + def_file)

# Parse to find the child nodes list of node 'myNode'
fwdefs = find_in_tree(root,"myNode")

මෙය " python xml parse " වෙතින්.


8

XML:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

පයිතන් කේතය:

import xml.etree.cElementTree as ET

tree = ET.parse("foo.xml")
root = tree.getroot() 
root_tag = root.tag
print(root_tag) 

for form in root.findall("./bar/type"):
    x=(form.attrib)
    z=list(x)
    for i in z:
        print(x[i])

ප්‍රතිදානය:

foo
1
2

7
import xml.etree.ElementTree as ET
data = '''<foo>
           <bar>
               <type foobar="1"/>
               <type foobar="2"/>
          </bar>
       </foo>'''
tree = ET.fromstring(data)
lst = tree.findall('bar/type')
for item in lst:
    print item.get('foobar')

මෙය foobarගුණාංගයේ අගය මුද්‍රණය කරයි .


6

xml.etree.ElementTree vs. lxml

මේවා වැඩිපුරම භාවිතා කළ පුස්තකාල දෙකේ වාසි කිහිපයක් වන අතර ඒවා තෝරා ගැනීමට පෙර දැන ගැනීමට මට හැකි වනු ඇත.

xml.etree.ElementTree:

  1. සිට සම්මත එකතුව ඕනෑම මොඩියුලය ස්ථාපනය කිසිදු අවශ්යතා:

lxml

  1. XML ප්‍රකාශය පහසුවෙන් ලියන්න : උදාහරණයක් ලෙස ඔබ එකතු කළ standalone="no"යුතුද?
  2. ලස්සන මුද්‍රණය : අමතර කේතයක් නොමැතිව ඔබට ලස්සන ඉන්ඩෙන්ට් කළ XML එකක් තිබිය හැකිය .
  3. ක්‍රියාකාරීත්වය වෛෂයික කරන්න : ඔබ සාමාන්‍ය පයිතන් වස්තු ධූරාවලියක් සමඟ ගනුදෙනු කරන ආකාරයට XML භාවිතා කිරීමට එය ඉඩ දෙයි .node.
  4. sourceline ඔබ භාවිතා කරන XML මූලද්‍රව්‍යයේ රේඛාව පහසුවෙන් ලබා ගැනීමට ඉඩ දෙයි.
  5. ඔබට බිල්ට් එක්ස්එස්ඩී ස්කීමා පරීක්ෂකයද භාවිතා කළ හැකිය.

5

මට පයිතන් xml.dom සහ xml.dom.minidom ඉතා පහසු බව පෙනේ. විශාල ප්‍රමාණයේ එක්ස්එම්එල් සඳහා DOM හොඳ නොවන බව මතක තබා ගන්න, නමුත් ඔබේ ආදානය තරමක් කුඩා නම් මෙය හොඳින් ක්‍රියාත්මක වේ.


2

තියෙනවා යම් lib විශේෂිත API භාවිතා කිරීමට කිසිදු අවශ්යතාවක් ඔබ භාවිතා කරන්නේ නම් python-benedict. ඔබගේ XML වෙතින් නව අවස්ථාවක් ආරම්භ කර එය dictඋප පංතියක් බැවින් පහසුවෙන් කළමනාකරණය කරන්න .

ස්ථාපනය පහසුය: pip install python-benedict

from benedict import benedict as bdict

# data-source can be an url, a filepath or data-string (as in this example)
data_source = """
<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>"""

data = bdict.from_xml(data_source)
t_list = data['foo.bar'] # yes, keypath supported
for t in t_list:
   print(t['@foobar'])

එය ආධාරක වන සහ normalizes බොහෝ ආකෘති සමඟ I / O මෙහෙයුම්: Base64, CSV, JSON, TOML, XML, YAMLහා query-string.

එය GitHub හි හොඳින් පරීක්ෂා කර විවෘත මූලාශ්‍රයකි .


0
#If the xml is in the form of a string as shown below then
from lxml  import etree, objectify
'''sample xml as a string with a name space {http://xmlns.abc.com}'''
message =b'<?xml version="1.0" encoding="UTF-8"?>\r\n<pa:Process xmlns:pa="http://xmlns.abc.com">\r\n\t<pa:firsttag>SAMPLE</pa:firsttag></pa:Process>\r\n'  # this is a sample xml which is a string


print('************message coversion and parsing starts*************')

message=message.decode('utf-8') 
message=message.replace('<?xml version="1.0" encoding="UTF-8"?>\r\n','') #replace is used to remove unwanted strings from the 'message'
message=message.replace('pa:Process>\r\n','pa:Process>')
print (message)

print ('******Parsing starts*************')
parser = etree.XMLParser(remove_blank_text=True) #the name space is removed here
root = etree.fromstring(message, parser) #parsing of xml happens here
print ('******Parsing completed************')


dict={}
for child in root: # parsed xml is iterated using a for loop and values are stored in a dictionary
    print(child.tag,child.text)
    print('****Derving from xml tree*****')
    if child.tag =="{http://xmlns.abc.com}firsttag":
        dict["FIRST_TAG"]=child.text
        print(dict)


### output
'''************message coversion and parsing starts*************
<pa:Process xmlns:pa="http://xmlns.abc.com">

    <pa:firsttag>SAMPLE</pa:firsttag></pa:Process>
******Parsing starts*************
******Parsing completed************
{http://xmlns.abc.com}firsttag SAMPLE
****Derving from xml tree*****
{'FIRST_TAG': 'SAMPLE'}'''

කරුණාකර ඔබේ පිළිතුර ගැටළුව විසඳන්නේ කෙසේද යන්න පැහැදිලි කරන සන්දර්භයක් ද ඇතුළත් කරන්න. කේත පමණක් පිළිතුරු දිරිමත් නොකෙරේ.
පෙඩ්‍රම් පාර්සියන්

-1

ප්‍රභවය xml ගොනුවක් නම්, මෙම නියැදිය මෙන් කියන්න

<pa:Process xmlns:pa="http://sssss">
        <pa:firsttag>SAMPLE</pa:firsttag>
    </pa:Process>

ඔබට පහත කේතය උත්සාහ කළ හැකිය

from lxml import etree, objectify
metadata = 'C:\\Users\\PROCS.xml' # this is sample xml file the contents are shown above
parser = etree.XMLParser(remove_blank_text=True) # this line removes the  name space from the xml in this sample the name space is --> http://sssss
tree = etree.parse(metadata, parser) # this line parses the xml file which is PROCS.xml
root = tree.getroot() # we get the root of xml which is process and iterate using a for loop
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue  # (1)
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]

dict={}  # a python dictionary is declared
for elem in tree.iter(): #iterating through the xml tree using a for loop
    if elem.tag =="firsttag": # if the tag name matches the name that is equated then the text in the tag is stored into the dictionary
        dict["FIRST_TAG"]=str(elem.text)
        print(dict)

ප්‍රතිදානය වනු ඇත

{'FIRST_TAG': 'SAMPLE'}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.