Nhận phần tử con python xml

Hướng dẫn này tổng quan ngắn gọn về các khái niệm chính của API ElementTree do LXML triển khai. etree và một số cải tiến đơn giản giúp cuộc sống của bạn với tư cách là một lập trình viên dễ dàng hơn

Một cách phổ biến để nhập lxml. etree như sau

>>> from lxml import etree

Nếu mã của bạn chỉ sử dụng API ElementTree và không dựa vào bất kỳ chức năng nào dành riêng cho LXML. etree, bạn cũng có thể sử dụng chuỗi nhập sau đây làm dự phòng cho ElementTree ban đầu

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"

Để hỗ trợ viết mã di động, hướng dẫn này làm rõ trong các ví dụ phần nào của API được trình bày là phần mở rộng của lxml. etree trên API ElementTree ban đầu, như được xác định bởi thư viện ElementTree của Fredrik Lundh

Phần tử là đối tượng vùng chứa chính cho API ElementTree. Hầu hết các chức năng của cây XML được truy cập thông qua lớp này. Các phần tử được tạo dễ dàng thông qua Element factory

>>> root = etree.Element["root"]

Tên thẻ XML của các phần tử được truy cập thông qua thuộc tính thẻ

>>> print root.tag
root

Các phần tử được tổ chức theo cấu trúc cây XML. Để tạo các phần tử con và thêm chúng vào phần tử cha, bạn có thể sử dụng phương thức append[]

>>> root.append[ etree.Element["child1"] ]

Tuy nhiên, một cách phổ biến và hiệu quả hơn nhiều để thực hiện việc này là thông qua SubElement factory. Nó chấp nhận các đối số giống như Element factory, nhưng cũng yêu cầu cha mẹ làm đối số đầu tiên

>>> child2 = etree.SubElement[root, "child2"]
>>> child3 = etree.SubElement[root, "child3"]

Để thấy rằng đây thực sự là XML, bạn có thể tuần tự hóa cây mà bạn đã tạo

>>> print etree.tostring[root, pretty_print=True]

  
  
  

Để truy cập vào các phần tử con này dễ dàng và đơn giản nhất có thể, các phần tử hoạt động chính xác như danh sách Python bình thường

>>> child = root[0]
>>> print child.tag
child1

>>> for child in root:
..     print child.tag
child1
child2
child3

>>> if root:
..     print "root has children!"
root has children!

>>> root.insert[0, etree.Element["child0"]]
>>> start = root[:1]
>>> end   = root[-1:]

>>> print start[0].tag
child0
>>> print end[0].tag
child3

>>> root[0] = root[-1]
>>> for child in root:
..     print child.tag
child3
child1
child2

Lưu ý cách phần tử cuối cùng được di chuyển đến một vị trí khác trong ví dụ trước. Đây là điểm khác biệt so với ElementTree ban đầu [và từ danh sách], nơi các phần tử có thể nằm ở nhiều vị trí của bất kỳ số lượng cây nào. trong lxml. etree, các phần tử chỉ có thể ngồi ở một vị trí của một cây tại một thời điểm

Nếu bạn muốn sao chép một phần tử sang một vị trí khác, hãy xem xét việc tạo một bản sao sâu độc lập bằng cách sử dụng mô-đun sao chép từ thư viện chuẩn của Python

________số 8

Để truy xuất danh sách Python 'thực' của tất cả các phần tử con [hoặc một bản sao nông của danh sách phần tử con của phần tử], bạn có thể gọi phương thức getchildren[]

>>> children = root.getchildren[]

>>> print type[children] is type[[]]
True

>>> for child in children:
..     print child.tag
child3
child1
child2

Đường đi lên của cây được cung cấp thông qua phương thức getparent[]

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
0

Anh chị em [hoặc hàng xóm] của một phần tử được truy cập dưới dạng các phần tử tiếp theo và trước đó

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
1

Các phần tử XML hỗ trợ các thuộc tính. Bạn có thể tạo chúng trực tiếp trong Element factory

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
2

Truy cập nhanh và trực tiếp vào các thuộc tính này được cung cấp bởi các phương thức set[] và get[] của các phần tử

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
3

Tuy nhiên, một cách rất thuận tiện để xử lý chúng là thông qua giao diện từ điển của thuộc tính attrib

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
4

Các phần tử có thể chứa văn bản

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
5

Trong nhiều tài liệu XML [được gọi là tài liệu tập trung vào dữ liệu], đây là nơi duy nhất có thể tìm thấy văn bản. Nó được đóng gói bởi một thẻ lá ở dưới cùng của cây phân cấp

Tuy nhiên, nếu XML được sử dụng cho các tài liệu văn bản được gắn thẻ chẳng hạn như [X]HTML, thì văn bản cũng có thể xuất hiện giữa các phần tử khác nhau, ngay ở giữa cây

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
6

Ở đây, thẻ được bao quanh bởi văn bản. Điều này thường được gọi là XML kiểu tài liệu. Các phần tử hỗ trợ điều này thông qua thuộc tính đuôi của chúng. Nó chứa văn bản trực tiếp theo sau phần tử, cho đến phần tử tiếp theo trong cây XML.
tag is surrounded by text. This is often referred to as document-style XML. Elements support this through their tail property. It contains the text that directly follows the element, up to the next element in the XML tree:

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
7

Hai thuộc tính này đủ để biểu diễn bất kỳ nội dung văn bản nào trong tài liệu XML. Tuy nhiên, nếu bạn muốn đọc văn bản mà không có các thẻ trung gian, bạn phải nối đệ quy tất cả các thuộc tính văn bản và đuôi theo đúng thứ tự. Một cách đơn giản hơn để làm điều này là XPath

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
8

Nếu bạn muốn sử dụng cái này thường xuyên hơn, bạn có thể bọc nó trong một hàm

try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
9

Đối với các vấn đề như trên, nơi bạn muốn duyệt qua cây một cách đệ quy và làm điều gì đó với các phần tử của nó, phép lặp cây là một giải pháp rất thuận tiện. Các phần tử cung cấp một trình lặp cây cho mục đích này. Nó mang lại các phần tử theo thứ tự tài liệu, tôi. e. theo thứ tự các thẻ của chúng sẽ xuất hiện nếu bạn tuần tự hóa cây thành XML

>>> root = etree.Element["root"]

Nếu bạn biết bạn chỉ quan tâm đến một thẻ duy nhất, bạn có thể chuyển tên của nó cho getiterator[] để nó lọc cho bạn

>>> root = etree.Element["root"]

trong lxml. etree, các phần tử cung cấp thêm các trình vòng lặp cho tất cả các hướng trong cây. con cái, cha mẹ [hay đúng hơn là tổ tiên] và anh chị em

Phần tử phụ trong XML là gì?

SubElement là một chức năng của ElementTree [không phải Element] cho phép bạn tạo các đối tượng con cho Element a function of ElementTree [not Element] which allows to create child objects for an Element . attrib lấy một từ điển chứa các thuộc tính của phần tử bạn muốn tạo.

XML Etree là gì?

Xml. cây etree. Mô-đun ElementTree triển khai API đơn giản và hiệu quả để phân tích cú pháp và tạo dữ liệu XML . Đã thay đổi trong phiên bản. 3. Mô-đun này sẽ sử dụng triển khai nhanh bất cứ khi nào có sẵn.

XML được sử dụng như thế nào trong Python?

Thư viện chuẩn Python cung cấp một bộ giao diện tối thiểu nhưng hữu ích để làm việc với XML . Hai API cơ bản và được sử dụng rộng rãi nhất cho dữ liệu XML là giao diện SAX và DOM. API đơn giản cho XML [SAX] − Tại đây, bạn đăng ký các cuộc gọi lại cho các sự kiện quan tâm và sau đó để trình phân tích cú pháp tiến hành thông qua tài liệu.

Vai trò của hàm parse[] trong ElementTree là gì?

Phân tích đối tượng tệp hoặc tên tệp bằng parse[] trả về một phiên bản của ET. Lớp ElementTree, đại diện cho toàn bộ hệ thống phân cấp phần tử . Mặt khác, phân tích cú pháp một chuỗi bằng fromstring[] sẽ trả về gốc cụ thể ET.

Chủ Đề