本文主要分享的是循环方法的使用,设置XML节点属性,用了3种循环方法。
XML文件:
<?xml version=‘1.0‘ encoding=‘utf-8‘ ?>
<root>
<seqs>
<seq name="a" license="1" enable="true"/>
<seq name="b" license="1" enable="true"/>
</seqs>
</root>
第一种方法:以vecSeq大小作为循环条件,最方便,因为可以直接使用int i
#include <iostream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"
#include "boost/property_tree/xml_parser.hpp"
using namespace rapidxml;
struct SeqStruct
{
std::string seqName;
std::string seqLicense;
};
int main()
{
SeqStruct seqs;
std:: vector<SeqStruct> vecSeq;
seqs.seqName = "zhang";
seqs.seqLicense = "true";
vecSeq.push_back(seqs);
seqs.seqName = "liu";
seqs.seqLicense = "true";
vecSeq.push_back(seqs);
for(int i = 0; i < 2; i++)
{
std::cout <<vecSeq[i].seqName;
std::cout <<vecSeq[i].seqLicense;
std::cout << std::endl;
}
file<> fDoc("E:/UIMRIS/BRANCHES/uMR_MAIN/MAIN/Features/win32test/XMLFile6.xml");
std::cout << fDoc.data() << std::endl;
xml_document<> xmlDoc;
xmlDoc.parse<0>(fDoc.data());
xml_node<>* rootNode = xmlDoc.first_node();
xml_node<>* seqsNode = rootNode->first_node();
xml_node<>* seqNode = seqsNode->first_node();
for (int i = 0; i < vecSeq.size(); ++i)
{
xml_attribute<>* attrSeq = seqNode->first_attribute();
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqName.c_str()));
attrSeq = attrSeq->next_attribute();
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqLicense.c_str()));
seqNode = seqNode->next_sibling();
}
std::string text;
rapidxml::print(std::back_inserter(text), xmlDoc, 0);
std::cout<<text<<std::endl;
std::ofstream out("E:/UIMRIS/BRANCHES/uMR_MAIN/MAIN/Features/win32test/XMLFile7.xml");
if (!out.good())
{
std::cout<<"error";
}
out << text;
out.close();
getchar();
return 0;
}
第二种方法:以节点指向为循环,但是需要重新定义一个int i
int i = 0;
for (xml_node<>* seqNode = seqsNode->first_node(); seqNode != NULL; seqNode = seqNode->next_sibling())
{
xml_attribute<>* attrSeq = seqNode->first_attribute();
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqName.c_str()));
attrSeq = attrSeq->next_attribute();
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqLicense.c_str()));
i++;
}
第三种方法:节点属性也作为循环,因为有3个属性,只操作前两个属性,所以要加判断条件
int i = 0;
for (xml_node<>* seqNode = seqsNode->first_node(); seqNode != NULL; seqNode = seqNode->next_sibling())
{
for (xml_attribute<>* attrSeq = seqNode->first_attribute(); attrSeq->next_attribute() != NULL; attrSeq = attrSeq->next_attribute()) //only change 2 attribute
{
if (bFirst)
{
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqName.c_str()));
bFirst = false;
}
else
{
attrSeq->value(xmlDoc.allocate_string(vecSeq[i].seqLicense.c_str()));
bFirst = true;
}
}
i++;
}