PySide6.QtXml.QDomDocument¶
- class QDomDocument¶
- The - QDomDocumentclass represents an XML document.- Details- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - The - QDomDocumentclass represents the entire XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document’s data.- Since elements, text nodes, comments, processing instructions, etc., cannot exist outside the context of a document, the document class also contains the factory functions needed to create these objects. The node objects created have an - ownerDocument()function which associates them with the document within whose context they were created. The DOM classes that will be used most often are- QDomNode,- QDomDocument,- QDomElementand- QDomText.- The parsed XML is represented internally by a tree of objects that can be accessed using the various QDom classes. All QDom classes only reference objects in the internal tree. The internal objects in the DOM tree will get deleted once the last QDom object referencing them or the - QDomDocumentitself is deleted.- Creation of elements, text nodes, etc. is done using the various factory functions provided in this class. Using the default constructors of the QDom classes will only result in empty objects that cannot be manipulated or inserted into the Document. - The - QDomDocumentclass has several functions for creating document data, for example,- createElement(),- createTextNode(),- createComment(),- createCDATASection(),- createProcessingInstruction(),- createAttribute()and- createEntityReference(). Some of these functions have versions that support namespaces, i.e.- createElementNS()and- createAttributeNS(). The- createDocumentFragment()function is used to hold parts of the document; this is useful for manipulating for complex documents.- The entire content of the document is set with - setContent(). This function parses the string it is passed as an XML document and creates the DOM tree that represents the document. The root element is available using- documentElement(). The textual representation of the document can be obtained using- toString().- Note - The DOM tree might end up reserving a lot of memory if the XML document is big. For such documents, the QXmlStreamReader class might be a better solution. - It is possible to insert a node from another document into the document using - importNode().- You can obtain a list of all the elements that have a particular tag with - elementsByTagName()or with- elementsByTagNameNS().- The QDom classes are typically used as follows: - doc = QDomDocument("mydocument") file = QFile("mydocument.xml") if not file.open(QIODevice.OpenModeFlag.ReadOnly): return if not doc.setContent(file): file.close() return file.close() # print out the element names of all elements that are direct children # of the outermost element. docElem = doc.documentElement() n = docElem.firstChild() while not n.isNull(): e = n.toElement() # try to convert the node to an element. if not e.isNull(): print(qPrintable(e.tagName()), '\n' # the node really is an element.) n = n.nextSibling() # Here we append a new element to the end of the document elem = doc.createElement("img") elem.setAttribute("src", "myimage.png") docElem.appendChild(elem) - Once - docand- elemgo out of scope, the whole internal tree representing the XML document is deleted.- To create a document using DOM use code like this: - doc = QDomDocument() root = doc.createElement("MyML") doc.appendChild(root) tag = doc.createElement("Greeting") root.appendChild(tag) t = doc.createTextNode("Hello World") tag.appendChild(t) xml = doc.toString() - For further information about the Document Object Model see the Document Object Model (DOM) Level 1 and Level 2 Core Specifications. - See also - DOM Bookmarks Application - Synopsis¶- Methods¶- def - __init__()
- def - createComment()
- def - createElement()
- def - createTextNode()
- def - doctype()
- def - elementById()
- def - implementation()
- def - importNode()
- def - setContent()
- def - toByteArray()
- def - toString()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - class ParseOption¶
- (inherits - enum.Flag) This enum describes the possible options that can be used when parsing an XML document using the- setContent()method.- Constant - Description - QDomDocument.ParseOption.Default - No parse options are set. - QDomDocument.ParseOption.UseNamespaceProcessing - Namespace processing is enabled. - QDomDocument.ParseOption.PreserveSpacingOnlyNodes - Text nodes containing only spacing characters are preserved. - See also - Added in version 6.5. 
 - __init__()¶
 - Constructs an empty document. - __init__(document)
- Parameters:
- document – - QDomDocument
 
 - Constructs a copy of - document.- The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use - cloneNode().- __init__(doctype)
- Parameters:
- doctype – - QDomDocumentType
 
 - Creates a document with the document type - doctype.- See also - __init__(name)
- Parameters:
- name – str 
 
 - Creates a document and sets the name of the document type to - name.- Creates a new attribute called - namethat can be inserted into an element, e.g. using- setAttributeNode().- If - nameis not a valid XML name, the behavior of this function is governed by- InvalidDataPolicy.- See also - Creates a new attribute with namespace support that can be inserted into an element. The name of the attribute is - qNameand the namespace URI is- nsURI. This function also sets- prefix()and- localName()to appropriate values (depending on- qName).- If - qNameis not a valid XML name, the behavior of this function is governed by- InvalidDataPolicy.- See also - createCDATASection(data)¶
- Parameters:
- data – str 
- Return type:
 
 - Creates a new CDATA section for the string - valuethat can be inserted into the document, e.g. using- appendChild().- If - valuecontains characters which cannot be stored in a CDATA section, the behavior of this function is governed by- InvalidDataPolicy.- See also - createComment(data)¶
- Parameters:
- data – str 
- Return type:
 
 - Creates a new comment for the string - valuethat can be inserted into the document, e.g. using- appendChild().- If - valuecontains characters which cannot be stored in an XML comment, the behavior of this function is governed by- InvalidDataPolicy.- See also - createDocumentFragment()¶
- Return type:
 
 - Creates a new document fragment, that can be used to hold parts of the document, e.g. when doing complex manipulations of the document tree. - createElement(tagName)¶
- Parameters:
- tagName – str 
- Return type:
 
 - Creates a new element called - tagNamethat can be inserted into the DOM tree, e.g. using- appendChild().- If - tagNameis not a valid XML name, the behavior of this function is governed by- InvalidDataPolicy.- createElementNS(nsURI, qName)¶
- Parameters:
- nsURI – str 
- qName – str 
 
- Return type:
 
 - Creates a new element with namespace support that can be inserted into the DOM tree. The name of the element is - qNameand the namespace URI is- nsURI. This function also sets- prefix()and- localName()to appropriate values (depending on- qName).- If - qNameis an empty string, returns a null element regardless of whether the invalid data policy is set.- See also - createEntityReference(name)¶
- Parameters:
- name – str 
- Return type:
 
 - Creates a new entity reference called - namethat can be inserted into the document, e.g. using- appendChild().- If - nameis not a valid XML name, the behavior of this function is governed by- InvalidDataPolicy.- See also - createProcessingInstruction(target, data)¶
- Parameters:
- target – str 
- data – str 
 
- Return type:
 
 - Creates a new processing instruction that can be inserted into the document, e.g. using - appendChild(). This function sets the target for the processing instruction to- targetand the data to- data.- If - targetis not a valid XML name, or data if contains characters which cannot appear in a processing instruction, the behavior of this function is governed by- InvalidDataPolicy.- See also - Creates a text node for the string - valuethat can be inserted into the document tree, e.g. using- appendChild().- If - valuecontains characters which cannot be stored as character data of an XML document (even in the form of character references), the behavior of this function is governed by- InvalidDataPolicy.- See also - doctype()¶
- Return type:
 
 - Returns the document type of this document. - documentElement()¶
- Return type:
 
 - Returns the root element of the document. - elementById(elementId)¶
- Parameters:
- elementId – str 
- Return type:
 
 - Returns the element whose ID is equal to - elementId. If no element with the ID was found, this function returns a- null element.- Since the QDomClasses do not know which attributes are element IDs, this function returns always a - null element. This may change in a future version.- elementsByTagName(tagname)¶
- Parameters:
- tagname – str 
- Return type:
 
 - Returns a - QDomNodeList, that contains all the elements in the document with the name- tagname. The order of the node list is the order they are encountered in a preorder traversal of the element tree.- See also - elementsByTagNameNS(nsURI, localName)¶
- Parameters:
- nsURI – str 
- localName – str 
 
- Return type:
 
 - Returns a - QDomNodeListthat contains all the elements in the document with the local name- localNameand a namespace URI of- nsURI. The order of the node list is the order they are encountered in a preorder traversal of the element tree.- See also - implementation()¶
- Return type:
 
 - Returns a - QDomImplementationobject.- importNode(importedNode, deep)¶
 - Imports the node - importedNodefrom another document to this document.- importedNoderemains in the original document; this function creates a copy that can be used within this document.- This function returns the imported node that belongs to this document. The returned node has no parent. It is not possible to import - QDomDocumentand- QDomDocumentTypenodes. In those cases this function returns a- null node.- If - importedNodeis a- null node, a null node is returned.- If - deepis true, this function imports not only the node- importedNodebut its whole subtree; if it is false, only the- importedNodeis imported. The argument- deephas no effect on- QDomAttrand- QDomEntityReferencenodes, since the descendants of- QDomAttrnodes are always imported and those of- QDomEntityReferencenodes are never imported.- The behavior of this function is slightly different depending on the node types: - Node Type - Behavior - The owner element is set to 0 and the specified flag is set to true in the generated attribute. The whole subtree of - importedNodeis always imported for attribute nodes:- deephas no effect.- Document nodes cannot be imported. - If - deepis true, this function imports the whole document fragment; otherwise it only generates an empty document fragment.- Document type nodes cannot be imported. - Attributes for which - specified()is true are also imported, other attributes are not imported. If- deepis true, this function also imports the subtree of- importedNode; otherwise it imports only the element node (and some attributes, see above).- Entity nodes can be imported, but at the moment there is no way to use them since the document type is read-only in DOM level 2. - Descendants of entity reference nodes are never imported: - deephas no effect.- Notation nodes can be imported, but at the moment there is no way to use them since the document type is read-only in DOM level 2. - The target and value of the processing instruction is copied to the new node. - The text is copied to the new node. - The text is copied to the new node. - The text is copied to the new node. - setContent(data[, options=QDomDocument.ParseOption.Default])¶
- Parameters:
- data – str 
- options – Combination of - ParseOption
 
- Return type:
 
 - setContent(device[, options=QDomDocument.ParseOption.Default])
- Parameters:
- device – - QIODevice
- options – Combination of - ParseOption
 
- Return type:
 
 - setContent(reader[, options=QDomDocument.ParseOption.Default])
- Parameters:
- reader – - QXmlStreamReader
- options – Combination of - ParseOption
 
- Return type:
 
 - setContent(data[, options=QDomDocument.ParseOption.Default])
- Parameters:
- data – - QByteArray
- options – Combination of - ParseOption
 
- Return type:
 
 - setContent(dev)
- Parameters:
- dev – - QIODevice
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overload returning - ParseResultinstead.- This function reads the XML document from the IO device - dev, returning true if the content was successfully parsed; otherwise returns- false.- No namespace processing is performed. - setContent(text)
- Parameters:
- text – - QByteArray
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overload returning - ParseResultinstead.- This function reads the XML document from the byte array - buffer, returning true if the content was successfully parsed; otherwise returns false.- No namespace processing is performed. - setContent(text)
- Parameters:
- text – str 
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overload returning - ParseResultinstead.- This function reads the XML document from the string - text, returning true if the content was successfully parsed; otherwise returns- false. Since- textis already a Unicode string, no encoding detection is performed.- No namespace processing is performed either. - setContent(dev, namespaceProcessing)
- Parameters:
- dev – - QIODevice
- namespaceProcessing – bool 
 
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overload taking - ParseOptionsinstead.- This function reads the XML document from the IO device - dev, returning true if the content was successfully parsed; otherwise returns- false.- Note - This method will try to open - devin read-only mode if it is not already open. In that case, the caller is responsible for calling close. This will change in Qt 7, which will no longer open- dev. Applications should therefore open the device themselves before calling- setContent.- setContent(reader, namespaceProcessing[, errorMsg=None[, errorLine=None[, errorColumn=None]]])
- Parameters:
- reader – - QXmlStreamReader
- namespaceProcessing – bool 
- errorMsg – str 
- errorLine – int 
- errorColumn – int 
 
- Return type:
- bool 
 - Note - This function is deprecated. 
 - Use the overload taking - ParseOptionsinstead.- This function reads the XML document from the QXmlStreamReader - readerand parses it. Returns- trueif the content was successfully parsed; otherwise returns- false.- If - namespaceProcessingis- true, the parser recognizes namespaces in the XML file and sets the prefix name, local name and namespace URI to appropriate values. If- namespaceProcessingis- false, the parser does no namespace processing when it reads the XML file.- If a parse error occurs, the error message is placed in - *- errorMsg, the line number in- *- errorLineand the column number in- *- errorColumn(unless the associated pointer is set to- nullptr).- See also - setContent(text, namespaceProcessing)
- Parameters:
- text – - QByteArray
- namespaceProcessing – bool 
 
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overload taking - ParseOptionsinstead.- This function parses the XML document from the byte array - dataand sets it as the content of the document. It tries to detect the encoding of the document as required by the XML specification.- If - namespaceProcessingis true, the parser recognizes namespaces in the XML file and sets the prefix name, local name and namespace URI to appropriate values. If- namespaceProcessingis false, the parser does no namespace processing when it reads the XML file.- If a parse error occurs, this function returns - falseand the error message is placed in- *- errorMsg, the line number in- *- errorLineand the column number in- *- errorColumn(unless the associated pointer is set to- nullptr); otherwise this function returns- true.- If - namespaceProcessingis true, the function- prefix()returns a string for all elements and attributes. It returns an empty string if the element or attribute has no prefix.- Text nodes consisting only of whitespace are stripped and won’t appear in the - QDomDocument.- If - namespaceProcessingis false, the functions- prefix(),- localName()and- namespaceURI()return an empty string.- Entity references are handled as follows: - References to internal general entities and character entities occurring in the content are included. The result is a - QDomTextnode with the references replaced by their corresponding entity values.
- References to parameter entities occurring in the internal subset are included. The result is a - QDomDocumentTypenode which contains entity and notation declarations with the references replaced by their corresponding entity values.
- Any general parsed entity reference which is not defined in the internal subset and which occurs in the content is represented as a - QDomEntityReferencenode.
- Any parsed entity reference which is not defined in the internal subset and which occurs outside of the content is replaced with an empty string. 
- Any unparsed entity reference is replaced with an empty string. 
 - See also - namespaceURI()- localName()- prefix()- isEmpty()- setContent(text, namespaceProcessing)
- Parameters:
- text – str 
- namespaceProcessing – bool 
 
- Return type:
- (retval, errorMsg, errorLine, errorColumn) 
 - Note - This function is deprecated. 
 - Use the overloads taking - ParseOptionsinstead.- This function reads the XML document from the string - text, returning true if the content was successfully parsed; otherwise returns- false. Since- textis already a Unicode string, no encoding detection is done.- toByteArray([indent=1])¶
- Parameters:
- indent – int 
- Return type:
 
 - Converts the parsed document back to its textual representation and returns a QByteArray containing the data encoded as UTF-8. - This function uses - indentas the amount of space to indent subelements.- See also - toString([indent=1])¶
- Parameters:
- indent – int 
- Return type:
- str 
 
 - Converts the parsed document back to its textual representation. - This function uses - indentas the amount of space to indent subelements.- If - indentis -1, no whitespace at all is added.- class ParseResult¶
- The struct is used to store the result of - setContent().- Details- The - ParseResultstruct is used for storing the result of- setContent(). If an error is found while parsing an XML document, the message, line and column number of an error are stored in- ParseResult.- See also - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - PySide6.QtXml.QDomDocument.ParseResult.errorMessage¶
 - PySide6.QtXml.QDomDocument.ParseResult.errorLine¶
 - PySide6.QtXml.QDomDocument.ParseResult.errorColumn¶