1)QDomElement::elementsByTagName 你是一个骗子,为什么孙子的也返回呀。
2) w
QDebug operator<<(QDebug dbg,const QDomNode& node) { QString s; QTextStream str(&s,QIODevice::WriteOnly); node.save(str,2); dbg << qPrintable(s); return dbg; }
3)
<?xml version="1.0" encoding="UTF-8"?>
<test attribute1="attribute1_context" attribute2="attribute2_context">
<child>domText</child>
domText2
</test>
一个规范的XML文档,是用XML说明开始的,主要由各元素组成。XML文档第一个元素就是根元素,XML文档必须有且只有一个根元素。元素是可以嵌套的
4)convert QDomElementto QDomDocument
// element is the QDomElement object QString str; QTextStream stream(&str,QIODevice::WriteOnly); element.save(stream,2); // stored the content of QDomElement to stream QDomDocument doc; doc.setContent(str.toUtf8()); // converted the QString to QByteArray
5)
例子:xml写
#include <QtXml/QDomDocument> #include <QtXml/QDomElement> #include <QtXml/QDomText> #include <QFile> #include <QTextStream> #include <QDebug> void writeXML() { QDomDocument doc; doc.appendChild( doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"")); QDomElement root = doc.createElement("test"); root.setAttribute( "attribute1","attribute1_context" ); root.setAttribute( "attribute2","attribute2_context" ); doc.appendChild(root); QDomText domText = doc.createTextNode("domText"); QDomText domText2 = doc.createTextNode("domText2"); QDomElement child = doc.createElement("child"); root.appendChild(child); child.appendChild(domText); root.appendChild(domText2); QFile file("writeXML.xml"); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate |QIODevice::Text)) return ; QTextStream out(&file); out.setCodec("UTF-8"); doc.save(out,4,QDomNode::EncodingFromTextStream); file.close(); } void readXML() { QDomDocument doc; QFile file("writeXML.xml"); if (!file.open(QIODevice::ReadOnly)) return; if (!doc.setContent(&file)) { file.close(); return; } file.close(); QDomNode firstNode = doc.firstChild(); qDebug() << firstNode.nodeName() << firstNode.nodeValue(); QDomElement docElem = doc.documentElement(); qDebug() << qPrintable(docElem.tagName()) << docElem.attribute( QString("attribute1"),QString("unknow") ); QDomNamedNodeMap attributes = docElem.attributes(); int length = attributes.length(); for( int index = 0; index < length; index++ ) { QDomNode node = attributes.item(index); QDomAttr domAttr = node.toAttr(); qDebug() << domAttr.name() << domAttr.value(); } QDomNode n = docElem.firstChild(); while(!n.isNull()) { if (n.isElement()) { QDomElement e = n.toElement(); qDebug() << qPrintable(e.tagName()); } else if (n.isText()) { qDebug()<<"isText"<<n.nodeValue(); } n = n.nextSibling(); } }