How to create/write a simple XML parser from scratch?

后端 未结 6 915
你的背包
你的背包 2021-02-01 15:44

How to create/write a simple XML parser from scratch?

Rather than code samples, I want to know what are the simplified, basic steps in English.

How is a good par

6条回答
  •  盖世英雄少女心
    2021-02-01 16:31

    A parser must fit the needs of your input language. In your case, simple XML. The first thing to know about XML is that it is context-free and absolutely not ambiguous, everything is wrapped between two tokens, and this is what makes XML famous: it is easy to parse. Finally, XML is always simply represented by a tree structure. As stated, you can simply parse your XML and execute code in the meantime, or parse the XML, generating the tree, and then execute code according to this tree.

    D provides a very interesting way to write an XML parser very easily, for example:

    doc.onStartTag["pointlight"] = (ElementParser xml)
    {
      debug writefln("Parsing pointlight element");
    
      auto l = new DistantLight(to!int(xml.tag.attr["x"]),
                                to!int(xml.tag.attr["y"]),
                                to!int(xml.tag.attr["z"]),
                                to!ubyte(xml.tag.attr["red"]),
                                to!ubyte(xml.tag.attr["green"]),
                                to!ubyte(xml.tag.attr["blue"]));
      lights ~= l;
    
      xml.parse();
    };
    

提交回复
热议问题