python将字符串写入xml中_lxml / dom.minidom 读写XML字符 | Python

本文介绍了如何使用Python的lxml库创建XML元素,并展示了添加子元素、设置文本、以及通过ElementTree序列化XML的方法。内容包括Element的属性和方法,如find、findall、findtext等,以及如何将XML写入文件。
摘要由CSDN通过智能技术生成

from lxml importetree

root= etree.Element("root")print(root, dir(root))

child1= etree.SubElement(root, "sub1")

child2= etree.SubElement(root, "sub2")

child2.text= "sub_text2"child3= etree.SubElement(root, "sub3")

child3.text= "sub_text3"

#addprevious/addnext

child1.addprevious(child2)

child1.addnext(child3)

sub_child1= etree.SubElement(child1, "sub_child1")#append()

child1.append(sub_child1)#print(dir(child))

#'addnext', 'addprevious', 'append', 'attrib', 'base', 'clear', 'cssselect', 'extend',#'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'getnext', 'getparent',#'getprevious', 'getroottree', 'index', 'insert', 'items', 'iter', 'iterancestors',#'iterchildren', 'iterdescendants', 'iterfind', 'itersiblings', 'itertext', 'keys',#'makeelement', 'nsmap', 'prefix', 'remove', 'replace', 'set', 'sourceline', 'tag',#'tail', 'text', 'values', 'xpath'

#clear()#Resets an element. This function removes all subelements, clears all attributes and sets the text and tail properties to None.#重置元素,清除子元素文本以及属性。

#cssselect()#css选择器方式

#extend()

#find()#Finds the first matching subelement, by tag name or path.

#findall()#Finds all matching subelements, by tag name or path.

#findtext()#Finds text for the first matching subelement, by tag name or path.

#get()#Gets an element attribute.

#getiterator()#a sequence or iterator of all elements in the subtree

#getnext()#Returns the following sibling of this element or None.

#getparent()#Returns the parent of this element or None for the root element.

#getprevious()#Returns the preceding sibling of this element or None.

#getroottree()#Return an ElementTree for the root node of the document that contains this element.

#index(self, child, start=None, stop=None)#Find the position of the child within the parent

#insert(self, index, element)#Inserts a subelement at the given position in this element

#items()#Gets element attributes, as a sequence.

#iter()#Iterate over all elements in the subtree in document order

#iterancestors()#Iterate over the ancestors of this element (from parent to parent).

#iterchildren()/iterdescendants()

#iterfind()

#itersiblings()

#itertext()

#keys()#Gets a list of attribute names.

#makeelement()#Creates a new element associated with the same document.

#remove(element)#Removes a matching subelement.

#replace(self, old_element, new_element)

#set(self, key, value)#Sets an element attribute.

#values()#Gets element attribute values as a sequence of strings.

#xpath()

#attrib#base#nsmap#prefix#sourceline#tag#tail#text

print(etree.tostring(root))print(dir(etree))#'AncestorsIterator', 'AttributeBasedElementClassLookup', 'C14NError', 'CDATA', 'Comment', 'CommentBase',#'CustomElementClassLookup', 'DEBUG', 'DTD', 'DTDError', 'DTDParseError', 'DTDValidateError', 'DocInfo',#'DocumentInvalid', 'ETCompatXMLParser', 'ETXPath', 'Element', 'ElementBase', 'ElementChildIterator',#'ElementClassLookup', 'ElementDefaultClassLookup', 'ElementDepthFirstIterator', 'ElementNamespaceClassLookup',#'ElementTextIterator', 'ElementTree', 'Entity', 'EntityBase', 'Error', 'ErrorDomains', 'ErrorLevels', 'ErrorTypes',#'Extension', 'FallbackElementClassLookup', 'FunctionNamespace', 'HTML', 'HTMLParser', 'HTMLPullParser',#'LIBXML_COMPILED_VERSION', 'LIBXML_VERSION', 'LIBXSLT_COMPILED_VERSION', 'LIBXSLT_VERSION', 'LXML_VERSION',#'LxmlError', 'LxmlRegistryError', 'LxmlSyntaxError', 'NamespaceRegistryError', 'PI', 'PIBase', 'ParseError',#'ParserBasedElementClassLookup', 'ParserError', 'ProcessingInstruction', 'PyErrorLog', 'PythonElementClassLookup',#'QName', 'RelaxNG', 'RelaxNGError', 'RelaxNGErrorTypes', 'RelaxNGParseError', 'RelaxNGValidateError', 'Resolver',#'Schematron', 'SchematronError', 'SchematronParseError', 'SchematronValidateError', 'SerialisationError',#'SiblingsIterator', 'SubElement', 'TreeBuilder', 'XInclude', 'XIncludeError', 'XML', 'XMLDTDID', 'XMLID',#'XMLParser', 'XMLPullParser', 'XMLSchema', 'XMLSchemaError', 'XMLSchemaParseError', 'XMLSchemaValidateError',#'XMLSyntaxError', 'XMLTreeBuilder', 'XPath', 'XPathDocumentEvaluator', 'XPathElementEvaluator', 'XPathError',#'XPathEvalError', 'XPathEvaluator', 'XPathFunctionError', 'XPathResultError', 'XPathSyntaxError', 'XSLT',#'XSLTAccessControl', 'XSLTApplyError', 'XSLTError', 'XSLTExtension', 'XSLTExtensionError', 'XSLTParseError',#'XSLTSaveError', '_Attrib', '_BaseErrorLog', '_Comment', '_Document', '_DomainErrorLog', '_Element',#'_ElementIterator', '_ElementMatchIterator', '_ElementStringResult', '_ElementTagMatcher', '_ElementTree',#'_ElementUnicodeResult', '_Entity', '_ErrorLog', '_FeedParser', '_IDDict', '_ListErrorLog', '_LogEntry',#'_ProcessingInstruction', '_RotatingErrorLog', '_SaxParserTarget', '_TargetParserResult', '_Validator',#'_XPathEvaluatorBase', '_XSLTProcessingInstruction', '_XSLTResultTree', 'adopt_external_document',#'cleanup_namespaces', 'clear_error_log', 'dump', 'fromstring', 'fromstringlist', 'get_default_parser',#'htmlfile', 'iselement', 'iterparse', 'iterwalk', 'memory_debugger', 'parse', 'parseid', 'register_namespace',#'set_default_parser', 'set_element_class_lookup', 'strip_attributes', 'strip_elements', 'strip_tags', 'tostring',#'tostringlist', 'tounicode', 'use_global_python_log', 'xmlfile'

#tree = etree.ElementTree(root)#tree.write("test.xml", pretty_print=True, xml_declaration=True, encoding='utf-8')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值