QDomDocument类表示整个XML文档。从概念上讲,它是文档树的根,并提供对文档数据的主要访问。由于元素、文本节点、注释、处理指令等不能存在于文档的上下文之外,因此文档类还包含创建这些对象所需的工厂函数。创建的节点对象有一个ownerDocument()函数,该函数将节点对象与创建节点的上下文中的文档关联起来。最常使用的DOM类是QDomNode、QDomDocument、QDomElement和QDomText。
文档的整个内容是用setContent()设置的。这个函数解析作为XML文档传递的字符串,并创建表示该文档的DOM树。根元素可以使用documentElement()。文档的文本表示可以使用toString()获得。
注意:如果XML文档很大,DOM树最终可能会保留大量内存。对于这样的文档,QXmlStreamReader或QXmlQuery类可能是更好的解决方案。
Qt的示例:
解析doc:
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()) << 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);
创建doc:
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();
MyTest:解析xml文件,遍历xml所有节点
void readDom(QString& filename){
QDomDocument doc("mydocument");
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
return;
if (!doc.setContent(&file)) {
file.close();
return;
}
file.close();
//文档根节点
QDomElement docElem = doc.documentElement();
//第一个子元素
QDomElement n = docElem.firstChildElement();
readDomNode(n);
}
void readDomNode(QDomNode& domNode)
{
QDomElement e = docElem.firstChildElement();
While(!e.isNull()){
readDomNode(n);
e = e.nextSiblingElement();
}
}