【问题标题】:End tag xml validation incorrect in Boost ptree read xmlBoost ptree 读取 xml 中的结束标记 xml 验证不正确
【发布时间】:2018-09-23 01:22:31
【问题描述】:

我正在尝试使用 C++ 中的 Boost Ptrees 进行一些简单的 xml 解析。但是,似乎read_xml 函数仅在不存在结束标记时才会引发错误。下面抛出一个错误。 例如:

<?xml version="1.0" encoding="utf-8"?>
<Grandparent>
<Parent>test<Parent>
</Grandparent>

注意 Parent 的结束标签没有右斜杠,这会作为错误抛出。即使没有像 &lt;Parent&gt;test 这样的结束标签也会引发预期的有效错误。

但是,如果结束标记字符串与开始标记字符串不匹配,它不会引发错误。例如:

<?xml version="1.0" encoding="utf-8"?>
<Grandparent>
<Parent>test</Child>
</Grandparent>

上面的解析很好。我的代码很简单,如下:

using boost::property_tree::ptree;
ptree pt;
read_xml(xmlpath, pt);

这里有什么我忽略的东西吗?

【问题讨论】:

    标签: c++ xml boost ptree


    【解决方案1】:

    是的。

    最重要的是:Boost Property Tree 不是 XML 库。

    其次,在后台使用的 rapidxml 实现将结束标记验证作为选择加入:

    if (Flags & parse_validate_closing_tags)
    {
        // Skip and validate closing tag name
        Ch *closing_name = text;
        skip<node_name_pred, Flags>(text);
        if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true))
            BOOST_PROPERTY_TREE_RAPIDXML_PARSE_ERROR("invalid closing tag name", text);
    }
    

    幸运的是,Boost Property 没有选择加入。事实上,它并没有让你选择加入:

    /// Text elements should be put in separate keys,
    /// not concatenated in parent data.
    static const int no_concat_text  = 0x1;
    /// Comments should be omitted.
    static const int no_comments     = 0x2;
    /// Whitespace should be collapsed and trimmed.
    static const int trim_whitespace = 0x4;
    
    inline bool validate_flags(int flags)
    {
        return (flags & ~(no_concat_text | no_comments | trim_whitespace)) == 0;
    }
    

    不允许使用其他标志。

    如果您需要 XML 解析,我建议您使用 XML 库。

    【讨论】:

    • 我想知道是否有一个 SAX xml 解析器,您可以建议它同时适用于 windows 和 linux?发现在 Windows 上运行 libxml2 非常困难。遇到各种库链接错误。
    • 我通常更喜欢 PugiXML。另见stackoverflow.com/questions/9387610/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2013-04-05
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多