为XML元素中的属性调用不同的处理函数

Jim*_*mmi 6 c++ xml

在C ++中处理XML属性时,应根据给定的属性使用什么来运行不同的操作?

目前,我有这样的事情:

// get list of attributes for an XML element into member called 'attributes'
// ...

// run appropriate functions for each attribute
for (auto attribute : attributes)
{
    auto name = attribute.name;
    auto value = attribute.value;

    if (name == "x")
        doSomethingWithX(value);
    else if (name == "y")
        doSomethingWithY(value);
}
Run Code Online (Sandbox Code Playgroud)

对于仅几个属性名称来说,这还不错-但是如果使用较大的属性名称(> 15),则看起来会变得凌乱,而且我担心性能问题。

有没有更好的方法来处理这样的属性?

πάν*_*ῥεῖ 2

您可以使用 astd::unordererd_map<std::string, std::function<void (const std::string&)>>并使用适当的 lambda 函数对其进行设置:

std::unordererd_map<std::string, std::function<void (const std::string&)>> attrProcessors = {
    { "X", [](const std::string& value) {
           // Do something with value
           } } } ,
    { "Y", [](const std::string& value) {
           // Do something with value
           } } }
};

// run appropriate functions for each attribute
for (auto attribute : attributes)
{
    auto name = attribute.name;
    auto value = attribute.value;

    auto processorEntry = attrProcessors.find(name);

    if(processorEntry != attrProcessors.end()) {
       (*processorEntry).second(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不太确定地图条目的维护会比if / else if级联更容易阅读。
另一方面,您不需要为每个属性名称创建额外的函数。