python xml解析ElementTree

*** three types:
** Element: store the elements with tag,attributes,chlid elements.
   ***SubElement:
   create: Element()
   modify: append,insert,remove
   list:   for node in root(Elements)
           etc:  nodes = node[1:5]
            node.append(subnode)
         node.insert(0, subnode)
         node.remove(subnode)
   Justify: if node is None:
          print "node not found"
   searching:
          1. find(pattern) returns the first subelement that matches the given pattern, or None if there is no matching element.
      2. findtext(pattern) returns the value of the text attribute for the first subelement that matches the given pattern. If there is no matching element, this method returns None.
          3. findall(pattern) returns a list (or another iterable object) of all subelements that match the given pattern.
      4. the pattern argument can either be a tag name, or a path expression
          5. getiterator(tag) returns a list (or another iterable object) which contains all subelements that has the given tag, on all levels in the subtree. The elements are returned in document order (that is, in the same order as they would appear if you saved the tree as an XML file).
      6. getiterator() (without argument) returns a list (or another iterable object) of all subelement in the subtree.
      7. getchildren() returns a list (or another iterable object) of all direct child elements. This method is deprecated; new code should use indexing or slicing to access the children, or list(elem) to get a list.
*** Attributes: Dict
   list:   elem = Element("tag")
          elem.attrib["first"] = "1"
       elem.attrib["second"] = "2"
   create: elem = Element("tag", first="1", second="2")
*** Text Content:
   list: elem = Element("tag")
         elem.text = "this element also contains text"
   justify: empty = "" | None

** ElementTree: used to read and write XML files.
   parse: from elementtree.ElementTree import parse
         tree = parse(filename| file object)
      elem = tree.getroot()
          this parse method returns an ElementTree object.
          or
          from elementtree.ElementTree import ElementTree
      tree = ElementTree(file=filename)
      elem = tree.getroot()
   write: from elementtree.ElementTree import Element, SubElement, ElementTree
         html = Element("html")
      body = SubElement(html, "body")
      ElementTree(html).write(outfile)
   convert: from elementtree.ElementTree import XML, fromstring, tostring
           elem = XML(text)
        elem = fromstring(text) # same as XML(text)
        text = tostring(elem)
            # convert the str to xml elements
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章