2013-01-16 25 views
1

文件test.yaml訪問YAML .....如何與複雜的按鍵

--- 
    map: 
     ? [L, itsy] : ISO_LOW_ITSY(out, in, ctrl) 
     ? [L, bitsy] : ISO_LOW_BITSY(out, in, ctrl) 
     ? [L, spider] : ISO_LOW_SPIDER(out, in, ctrl) 
     ? [H, ANY] : ISO_HIGH(out, in, ctrl) 

我可以用它來與YAML-CPP訪問其中的一個什麼命令。我可以作爲一個整體訪問地圖,但不能訪問個別元素。

這裏就是我想:

YAML::Node doc = YAML::LoadFile("test.yaml"); 
    std::cout << "A:" << doc["mapping"] << std::endl; 
    std::cout << "LS1:" << doc["mapping"]["[L, spider]"] << std::endl; 
    std::cout << "LS2:" << doc["mapping"]["L", "spider"] << std::endl; 

這裏是我的結果:

A:? ? - L 
      - itsy 
: ISO_LOW_ITSY(out, in, ctrl) 
: ~ 
? ? - L 
    - bitsy 
    : ISO_LOW_BITSY(out, in, ctrl) 
: ~ 
? ? - L 
    - spider 
    : ISO_LOW_SPIDER(out, in, ctrl) 
: ~ 
? ? - H 
    - ANY 
    : ISO_HIGH(out, in, ctrl) 
: ~ 
LS1: 
LS2: 

如果這還不在YAML-CPP可能,我想知道這一點。

回答

1

您必須定義與您的密鑰匹配的類型。例如,如果你的關鍵是兩個標量的序列:

struct Key { 
    std::string a, b; 

    Key(std::string A="", std::string B=""): a(A), b(B) {} 

    bool operator==(const Key& rhs) const { 
    return a == rhs.a && b == rhs.b; 
    } 
}; 

namespace YAML { 
    template<> 
    struct convert<Key> { 
    static Node encode(const Key& rhs) { 
     Node node; 
     node.push_back(rhs.a); 
     node.push_back(rhs.b); 
     return node; 
    } 

    static bool decode(const Node& node, Key& rhs) { 
     if(!node.IsSequence() || node.size() != 2) 
     return false; 

     rhs.a = node[0].as<std::string>(); 
     rhs.b = node[1].as<std::string>(); 
     return true; 
    } 
    }; 
} 

然後,如果你的YAML文件

? [foo, bar] 
: some value 

你可以寫:

YAML::Node doc = YAML::LoadFile("test.yaml"); 
std::cout << doc[Key("foo", "bar")];  // prints "some value" 

注:

我認爲你的YAML不會做你想要的。在塊上下文中,顯式鍵/值對必須位於單獨的行上。換句話說,你應該做的

? [L, itsy] 
: ISO_LOW_ITSY(out, in, ctrl) 

? [L, itsy] : ISO_LOW_ITSY(out, in, ctrl) 

後者使得一個鍵,與(隱含的)空值;即,這是一樣的

? [L, itsy] : ISO_LOW_ITSY(out, in, ctrl) 
: ~ 

(您可以通過YAML-CPP如何輸出的例子來看看這個。)請參閱the relevant area in the spec