【发布时间】:2011-02-28 15:07:20
【问题描述】:
我在使用 Qt DOM 和 XML 文件的 DTD 时遇到了困难。 假设我们有一个像下面这样的 xml 文件。 DTD 嵌入到文件中。
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE notes [
<!ELEMENT (note+)>
<!ELEMENT note (to,from,heading,message)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT message (#PCDATA)>
]>
<!-- modified w3schools example -->
<notes>
<note>
<to>Megatron</to>
<from>Pele</from>
<heading>Match</heading>
<message>Make sure you bring the beer!</message>
</note>
</notes>
如何从文件中读取 DTD,然后在编辑 DOM 树后将其写回同一个文件?
我遇到的问题是,如果我读取 xml 文件,我只会将根节点
我正在使用 Qt 4.7 和 C++。
编辑 1(基于帖子):
这就是我解析文件和导航 dom 树的方式。
QDomDocument notes;
if( !notes.setContent(&file) ){
file.close();
return -1;
}
file.close();
//Get root element.
//.documentElement() skips proc instr and DTD!
QDomElement re = notes.documentElement();
if( re.tagName() != "notes"){
qerr << "Err: Root element is not NOTES." << endl;
return -1;
}
nNote = re.firstChild();
while( !nNote.isNull() )
{
QDomElement eNote = nNote.toElement();
if( !eNote.isNull() && eNote.tagName() == "note" ){
//some work...
}
nNote = nNote.nextSibling();
}
请注意,这种方式不允许我处理
编辑 2(基于帖子):
//Based on QDomDocument notes;
qout << notes.doctype() << endl; //Only prints <!DOCTYPE notes
QDomDocumentType dt = notes.doctype();
qout << "(QDomDocumentType dt) has child nodes: " << dt.hasChildNodes() <<endl; //False
QDomNodeList children = notes.childNodes();
for ( int i=0; i < children.count(); ++i ) {
QDomNode child = children.at( i );
//Only proc & element nodes show! DTD node does not exist according to this loop.
qout << "Type of node is: " << child.nodeType() << endl;
qout << "Node is DTD: " << child.isDocumentType() << endl; //False.
}
【问题讨论】: