QDomdocument官方翻译:
QDomdocument代表了整个xml。常可以说,它是文档树的根节点,通常提供了基本访问文档数据据的接口。
因为元素,文本节点,注释,处理指令等,不能存在文本之外。可以通过QDomdocument中提供的工厂函数产生这些节点对象。节点对象拥有一个ownerDocument函数,该函数关联着创建这些节点对象,并包含其内容的document。Dom类使用最多的是 QDomNode,QDomDocument,QDomElement,QDomText.
解析的xml内部以树对象组织起来,能够通过各种各样的QDom类访问。所用的QDom类都是引用树内的对象。一旦最后一个引用他们的QDom对象,或者QDomDocument本身被删除,那么Dom树中内部对象将会删除。
元素,文本节点等创建,可以通过各种类中各种各样的工厂函数。使用一个默认QDom类的构造函数将会导致空的对象,以至于该对象不能操作以及插入到Document中。
QDomDocument类含有许多的成员函数,用来产生document数据。例如createElement(),createTextNode(),createComment(),createCDATASection(),createProcesssingInstruction(),createAttribute(),createEntityReference().在这些当中有些版本,例如createElementNS()和createAttibuteNA()。
createDocumentFragment()函数用来保存文档中部分内容。这是对操作复杂的document非常有用。
文档的内容可以通过函数setContent().这个函数将会解析被传递的xml字符串。同时形成代表document的DOM树。通过使用documentElement()获得root元素(根节点)。可以使用toString()获得文档的文本表示形式。
注意:
如果XML文档很大,DOM树可能会保留大量内存.对于这样文档,QXmlStreamReader或者QXmlQuery类可能是最好的解决方案。通过importNode()能将一个文档中一个节点插入到另一个文档。可以通过带有特定tagname的elementsByTagName()或者elementsByTagNameNs()获取一些元素链表。
使用举例(官方:)
QDomDocument doc("mydocument");
QFile file("mydocument.xml");
if (!file.open(QIODevice::ReadOnly))
return;
if (!doc.setContent(&file)) {
file.close();
return;
}
file.close();
// print out the element names of all elements that are direct children
// of the outermost element.
QDomElement docElem = doc.documentElement();
QDomNode n = docElem.firstChild();
while(!n.isNull()) {
QDomElement e = n.toElement(); // try to convert the node to an element.
if(!e.isNull()) {
cout << qPrintable(e.tagName()) << Qt::endl; // the node really is an element.
}
n = n.nextSibling();
}
// Here we append a new element to the end of the document
QDomElement elem = doc.createElement("img");
elem.setAttribute("src", "myimage.png");
docElem.appendChild(elem);
Once doc and elem go out of scope, the whole internal tree representing the XML document is deleted.
创建xml(官方):
to create a document using DOM use code like this:
QDomDocument doc("MyML");
QDomElement root = doc.createElement("MyML");
doc.appendChild(root);
QDomElement tag = doc.createElement("Greeting");
root.appendChild(tag);
QDomText t = doc.createTextNode("Hello World");
tag.appendChild(t);
QString xml = doc.toString();