How to use TinyXml to parse for a specific element

别说谁变了你拦得住时间么 提交于 2019-12-07 00:23:08

问题


I would like to parse a group of elements out of a TinyXml output. Essentially, I need to pick out any port element's "portid" attribute of the port has a state of "open" (shown below for port 23).

What's the best way to do this? Here's the (simplified) listing for the output from TinyXml:

<?xml version="1.0" ?>
<nmaprun>
    <host>
        <ports>
            <port protocol="tcp" portid="22">
                <state state="filtered"/>
            </port>
            <port protocol="tcp" portid="23">
                <state state="open "/>
            </port>
            <port protocol="tcp" portid="24">
                <state state="filtered" />
            </port>
            <port protocol="tcp" portid="25">
                <state state="filtered" />
            </port>
            <port protocol="tcp" portid="80">
                <state state="filtered" />
            </port>
        </ports>
    </host>
</nmaprun>

回答1:


This will roughly do it:

    TiXmlHandle docHandle( &doc );

    TiXmlElement* child = docHandle.FirstChild( "nmaprun" ).FirstChild( "host" ).FirstChild( "ports" ).FirstChild( "port" ).ToElement();

    int port;
    string state;
    for( child; child; child=child->NextSiblingElement() )
    {

        port = atoi(child->Attribute( "portid"));

        TiXmlElement* state_el = child->FirstChild()->ToElement();

        state = state_el->Attribute( "state" );

        if ("filtered" == state)
            cout << "port: " << port << " is filtered! " << endl;
        else
            cout << "port: " << port << " is unfiltered! " << endl;
    }



回答2:


Your best bet is to use the TinyXPath library in addition to TinyXML.

This is my best guess for the right XPath query:

/nmaprun/host/ports/port[state/@state="open"][1]/@portid

You can check it with an online tester.



来源:https://stackoverflow.com/questions/789817/how-to-use-tinyxml-to-parse-for-a-specific-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!