我正在尝试解码下面给出的一个 soap xml 数据包
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope>
<SOAP-ENV:Header><cwmp:ID SOAP-ENV:mustUnderstand="230">105</cwmp:ID>
</SOAP-ENV:Header>
<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cwmp:Request>
<Id>100</Id>
<RequestEvent SOAP-ENC:arrayType="cwmp:RequestStruct[3]">
<RequestStruct>
<Code>0 ZERO</Code>
<Key></Key>
</RequestStruct>
<RequestStruct>
<Code>1 ONE</Code>
<Key></Key>
</RequestStruct>
<RequestStruct>
<Code>2 TRAP</Code>
<Key></Key>
</RequestStruct>
</RequestEvent>
</cwmp:Request>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
当我尝试使用代码解码数据包时
BOOST_FOREACH(boost::property_tree::ptree::value_type &SL_vTemp, pt.get_child("SOAP-ENV:Envelope.SOAP-ENV:Body.cwmp:Request.RequestEvent"))
{
struct param obj;
obj._Name.assign(SL_vTemp.second.get<std::string>("Code"));
obj._Value.assign(SL_vTemp.second.get<std::string>("Key"))
}
我遇到异常,没有名为 EventCode 的节点。 但是,如果我从 soap xml 数据包中删除属性部分“SOAP-ENC:arrayType="cwmp:RequestStruct[3]",那么代码工作正常。 提前致谢。
最佳答案
你应该用一个条件包围这个 block 来检查它是RequestStruct
元素:
if (SL_vTemp.first == "RequestStruct")
{
auto code = SL_vTemp.second.get<std::string>("Code");
auto key = SL_vTemp.second.get<std::string>("Key");
std::cout << "code:" << code << " key:" << key << "\n";
}
因为属性在<xmlattr>
下在那里加前缀。
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <iostream>
extern std::string const sample;
int main() {
boost::property_tree::ptree pt;
{
std::istringstream iss(sample);
read_xml(iss, pt);
}
BOOST_FOREACH (boost::property_tree::ptree::value_type &SL_vTemp,
pt.get_child("SOAP-ENV:Envelope.SOAP-ENV:Body.cwmp:Request.RequestEvent"))
{
if (SL_vTemp.first == "RequestStruct")
{
auto code = SL_vTemp.second.get<std::string>("Code");
auto key = SL_vTemp.second.get<std::string>("Key");
std::cout << "code:" << code << " key:" << key << "\n";
} else
{
std::cout << "skipped: '" << SL_vTemp.first << "'\n";
}
}
}
std::string const sample = R"(
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope>
<SOAP-ENV:Header><cwmp:ID SOAP-ENV:mustUnderstand="230">105</cwmp:ID>
</SOAP-ENV:Header>
<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cwmp:Request>
<Id>100</Id>
<RequestEvent SOAP-ENC:arrayType="cwmp:RequestStruct[3]">
<RequestStruct>
<Code>0 ZERO</Code>
<Key>key0</Key>
</RequestStruct>
<RequestStruct>
<Code>1 ONE</Code>
<Key>key1</Key>
</RequestStruct>
<RequestStruct>
<Code>2 TRAP</Code>
<Key>key2</Key>
</RequestStruct>
</RequestEvent>
</cwmp:Request>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
)";
打印
skipped: '<xmlattr>'
code:0 ZERO key:key0
code:1 ONE key:key1
code:2 TRAP key:key2
关于c++ - boost 中的属性是如何解析的? SOAP xml 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749234/