我有一个非常恼人的问题,我正试图解决它很多个小时。 我正在使用带有C ++的rapidXML来解析XML文件:
xml_document<> xmlin;
stringstream input; //initialized somewhere else
xmlin.clear();
xmlin.parse<0>(&(input.str()[0]));
cout << "input:" << input.str() << endl << endl;
xml_node<char> *firstnode = xmlin.first_node();
string s_type = firstnode->first_attribute("type")->value();
cout << "type: " << s_type << endl;
但是我在stdout上得到了这个:
input:<?xml version="1.0" encoding="utf-8"?><testxml command="testfunction" type="exclusive" />
type: exclusive" />
这可能是什么原因(打印s_type变量)? 这非常烦人,因为我无法很好地处理xml。
答案 0 :(得分:1)
实际上我找到了解决方案。
Stringstream不喜欢它的内容被修改(rapidXML进行快速的原位解析,这意味着它会修改它获得的数组的内容)。
然而,在文档中,我读到字符串类也不喜欢它。
来自string :: c_str文档页面:
不应在程序中修改此数组中的值
但是当我从流中创建一个字符串时,它正如预期的那样工作:
xml_document<> xmlin;
stringstream input; //initialized somewhere else
string buffer = input.str()
xmlin.clear();
xmlin.parse<0>(&(buffer[0]));
答案 1 :(得分:0)
我认为问题出在您未显示的代码中...首先尝试使用文字字符串 - 这对我来说效果很好......
xml_document<> xmlin;
char *input = "<?xml version=\"1.0\" encoding=\"utf-8\"?><testxml command=\"testfunction\" type=\"exclusive\" />";
xmlin.parse<0>(input);
xml_node<char> *firstnode = xmlin.first_node();
std::string s_type = firstnode->first_attribute("type")->value();
答案 2 :(得分:0)
我个人推荐这种方法
xml_document<> doc;
string string_to_parse;
char* buffer = new char[str_to_parse.size() + 1];
strcpy (buffer, str_to_parse.c_str());
doc.parse<0>(buffer);
delete [] cstr;
从要解析的字符串中生成非const char
数组。我总是发现这种方式更安全,更可靠。
我曾经做过如此疯狂的事情
string string_to_parse;
doc.parse<0>(const_cast<char*>(string_to_parse.c_str()));
并且它“工作”了很长时间(直到我需要重用原始字符串的那一天)。由于RapidXML可以修改它正在解析的char数组,因为不建议通过str::string
更改c_str()
我总是使用将我的字符串复制到非const char数组的方法并将其传递给解析器。它可能不是最佳的并使用额外的内存,但它是可靠的,我迄今从未遇到任何错误或问题。您的数据将被解析,原始字符串可以重复使用,而不必担心它被修改。