2009-04-25 27 views
7

Tôi muốn phân tích một nhóm các phần tử ra khỏi một đầu ra TinyXml. Về cơ bản, tôi cần phải chọn ra bất kỳ thuộc tính "portid" của phần tử cổng nào có trạng thái là "open" (được hiển thị bên dưới cho cổng 23).Cách sử dụng TinyXml để phân tích cú pháp cho một phần tử cụ thể

Cách tốt nhất để làm điều này là gì? Dưới đây là (giản thể) niêm yết cho sản lượng từ 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> 

Trả lời

10

này xấp xỉ sẽ làm điều đó:

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; 
    } 
4

Tốt nhất là sử dụng thư viện TinyXPath ngoài TinyXML.

Đây là đoán tốt nhất của tôi cho XPath truy vấn ngay:

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

Bạn có thể kiểm tra nó với một online tester.

Các vấn đề liên quan