1.xml解析
xml文件解析有DOM, SAX方式。
DOM解析:
是相当于把整个xml结构以树形结构读进内存中。
优点:很方便实现增删改操作
缺点:如果文件过大,造成内存溢出
SAX解析:
采用事件驱动,边读边解析。
优点:如果文件过大,不会造成内存溢出,方便实现查询操作
缺点:不能实现增删改操作
2.使用Xerces库实现xml解析
Xerces库的下载,编译等参考博文:Xerces的下载,编译和在VS 2019中的配置
3.Xerces库使用说明(DOM解析)
红色的叫标签,蓝色的是标签的属性。
1.根据某个标签,获取整个标签中的内容。
XercesDOMParser* parser = new XercesDOMParser();
const char* xmlFile = "C:\\Users\\tianyanbin\\source\\repos\\MyXml\\MyXml\\test.xml";//绝对路径
parser->parse(xmlFile);
DOMDocument* doc = parser->getDocument();
DOMElement* m_pRoot = doc->getDocumentElement(); //获取XML根节点
DOMNodeList* pVersionEleList = m_pRoot->getElementsByTagName(XMLString::transcode("Sector"));//获取Sector节点
2.获取便签中某个属性的值
DOMNode* child001 = XXXX; //chilid001是某个结点,对应一个标签对象
DOMNamedNodeMap* pAttributes = child001->getAttributes(); //----------------取属性表
const XMLCh* attrDef = XMLString::transcode("ProcessParameter"); //----------------把属性名字符串转变一下存起来;
DOMNode* node = pAttributes->getNamedItem(attrDef); //---------------- - 根据属性名取出属性
XMLString::release((XMLCh**)(&attrDef)); //----------------记得和XMLString::transcode配对使用,否则内存泄露
char* pc = XMLString::transcode(node->getNodeValue()); // ----------------把属性转变为char*
cout << "ProcessParameter:" << pc << endl;
XMLString::release(&pc);//realse和
完成项目代码和xml文件:
test.xml:
<Group>
<Id>0</Id>
<Detail>
<SectorsNum>100</SectorsNum>
<Sector>
<Id>0</Id>
<Gun>
<Id>0</Id>
<DataBlock ProcessParameter="9" ReginId="2" Type="NormalPoly">
<PolyLine Count="8">193.784 27.234 0.000 193.731 26.621 -0.001 193.414 21.899 -0.011 193.189 17.245 -0.021 193.052 12.596 -0.031 193.004 7.983 -0.041 193.046 3.055 -0.052 193.131 0.000 -0.058</PolyLine>
<PolyLine Count="5">195.168 4.852 -0.058 196.265 4.867 -0.061 196.252 8.144 -0.068 195.153 8.148 -0.070 195.168 4.852 -0.077</PolyLine>
<PolyLine Count="5">196.253 8.544 -0.077 196.288 11.821 -0.084 195.189 11.837 -0.087 195.154 8.548 -0.094 196.253 8.544 -0.096</PolyLine>
<PolyLine Count="5">195.236 1.160 -0.096 196.335 1.188 -0.098 196.271 4.467 -0.105 195.172 4.452 -0.108 195.236 1.160 -0.115</PolyLine>
<PolyLine Count="5">196.297 12.220 -0.115 196.378 15.495 -0.122 195.278 15.532 -0.124 195.197 12.236 -0.131 196.297 12.220 -0.134</PolyLine>
<PolyLine Count="4">196.372 0.000 -0.134 196.345 0.788 -0.135 195.246 0.760 -0.138 195.272 0.000 -0.139</PolyLine>
<PolyLine Count="5">196.393 15.894 -0.139 196.524 19.171 -0.146 195.426 19.221 -0.149 195.293 15.931 -0.156 196.393 15.894 -0.158</PolyLine>
<PolyLine Count="5">196.545 19.568 -0.158 196.725 22.840 -0.165 195.627 22.906 -0.168 195.445 19.620 -0.175 196.545 19.568 -0.177</PolyLine>
<PolyLine Count="5">196.750 23.237 -0.177 196.978 26.504 -0.184 195.883 26.588 -0.186 195.653 23.305 -0.193 196.750 23.237 -0.196</PolyLine>
<PolyLine Count="3">195.962 27.540 -0.196 195.915 26.985 -0.197 197.011 26.902 -0.199</PolyLine>
<PolyLine Count="2">197.079 27.697 -0.199 197.011 26.902 -0.201</PolyLine>
<PolyLine Count="7">199.269 28.005 -0.201 199.003 24.686 -0.208 198.709 19.