2014-08-27 71 views
0

XML標籤我要解析的XML文件的格式如下:瀏覽通過使用QDomElement

<FirstTag> 
    <SecondTag> 
     <Attribute value="hello"/> 
    </SecondTag> 
</FirstTag> 

現在,這是我所:

QDomNode n = domElem.firstChild(); 
while(!n.isNull()){ 
    QDomElement e = n.toElement(); 
    if(!e.isNull()){ 
    if(e.tagName() == "FirstTag"){ 
     //secondtag??? 
    } 
    } 
n = n.nextSibling(); 
} 

現在我實際的問題: 我想要從SecondTag訪問屬性,我如何訪問它,因爲它的FirstTag子標籤我不能在我當前的循環中訪問它。

回答

0

看起來你錯過了QDomNode有子節點和一個函數childNodes()來獲取節點的子節點。

因此,如果QDomNode n指向第一個元素,而不是僅查找第一個Child,則獲取每個元素的子節點,檢查正確的節點名稱,然後檢查每個子節點的子節點。要獲得屬性,你可以這樣做: -

QString attribValue; 
QDomNodeList children = n.childNodes(); 

QDomNode childNode = children.firstChild(); 
while(!childNode.isNull()) 
{ 
    if(childNode.nodeName() == "Attribute") 
    { // there may be multiple attributes 
     QDomNamedNodeMap attributeMap = node.attributes(); 

     // Let's assume there is only one attribute this time 
     QDomAttr item = attributeMap.item(0).toAttr(); 
     if(item.name() == "value") 
     { 
      attribValue = item.value(); // which is the string "hello" 
     } 
    }  
} 

這可以通過遞歸函數來完成,對於每個節點及其子節點。

0

不要這樣做。首先使用documentElement()然後(在返回的對象上)使用elementsByTagName()搜索嵌套元素。

0

這是非常簡單的XML文檔,所以試試這個。此代碼的工作,只要你想

QDomDocument doc("mydocument"); 
QFile f("G:/x.txt"); 
if (!f.open(QIODevice::ReadOnly)) 
    qDebug() <<"fail"; 
if (!doc.setContent(&f)) { 
    f.close(); 
    qDebug() <<"fail"; 
} 
f.close(); 

QDomElement domElem = doc.documentElement();//FistTag here 
QDomNode n = domElem.firstChild();//seconTag here 
    QDomElement e = n.toElement(); 
    if(!e.isNull()){ 
     n = n.firstChild();//now it is attribute tag 

     e = n.toElement(); 
     qDebug() << e.attribute("value") <<"inside" << e.tagName(); 
    } 

輸出:"hello" inside "Attribute"