简体   繁体   中英

How to parse tags in java

Response from server is like this:

<oob>
   <type>screen</type>
   <value>idle</value>
   <action>show</action>
</oob>
<oob>
   <type>schedule</type>
   <action>show</action>
</oob>

I want to put all the tags as key and value inside tag as value. Numbers of tags and tag types are not known. I want something like this:

//for first string from server

public HashMap<String, String> response = new HashMap<String, String>();
response.put("type","screen");
response.put("value","idle");
response.put("action","show");

//for second string

response.put("type","schedule");
response.put("action","show");

There should be the logic to parse the string:

if(server_response.contains("<oob>")){
    while(!endof server_response)
    response.put("?","?");
}

How to parse server response in that format?

Use an XML parsing API, DOM API is one of the easiest to use but you will need to convert the string to a Document first.

You can convert the whole string to Node objects, using a loop, you can one by one check the expected elements for each (s) and put it to a collection.

Here's some code sample you can try:

DocumentBuilderFactory buildderfactory= DocumentBuilderFactory.newInstance();
    DocumentBuilder db =buildderfactory.newDocumentBuilder();


    Document docXml = db.parse(new InputSource( new StringReader( yourxml )));

    NodeList list = docXml.getElementsByTagName("oob");

    for (int i=0; i<list.getLength(); i++){

        System.out.println(i);


        Node n = list.item(i);
        Node child =n.getFirstChild();
        while(child!=null){

            System.out.println(child.getNodeName());
            System.out.println(child.getFirstChild().getNodeValue());
            child= child.getNextSibling();
        }

    }
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class DomParserDemo {
   public static void main(String[] args){

      try { 
         File inputFile = new File("input.txt");
         DocumentBuilderFactory dbFactory 
            = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element :" 
            + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("student");
         System.out.println("----------------------------");
         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" 
               + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               System.out.println("Student roll no : " 
                  + eElement.getAttribute("rollno"));
               System.out.println("type : " 
                  + eElement
                  .getElementsByTagName("type")
                  .item(0)
                  .getTextContent());
               System.out.println("value : " 
               + eElement
                  .getElementsByTagName("value")
                  .item(0)
                  .getTextContent());
               System.out.println("action: " 
               + eElement
                  .getElementsByTagName("action")
                  .item(0)
                  .getTextContent());

            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

have a look at this link too. http://www.tutorialspoint.com/java_xml/java_dom_parse_document.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM