如何解析包含XML标签的字符串,以便我可以获取所有子标签的值

问题描述:

我必须解析包含XML标签的字符串,如以下硬编码的字符串,以便我可以分别获取所有标签的值。在这里,当我使用如何解析包含XML标签的字符串,以便我可以获取所有子标签的值

NodeList node = doc.getElementsByTagName("event"); 

它返回值“ajain1AnkitJain24-04-199223:09.08”

我想检索每个标签的价值和在不同的变量单独存放。

像例如,在这种情况下我想存储的值:

String UID = ajain1 
String FirstName = Ankit 
String LastName = Jain 
Date date = "24-04-1992 23:09.08" 

下面是示例代码我的工作。

package test; 

import java.io.IOException; 
import java.io.StringReader; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

public class Demo { 

    public static void main(String[] args) { 

     String xmldata = "<event><class></class><data><UID><![CDATA[ajain1]]></UID><FIRSTNAME><![CDATA[Ankit]]></FIRSTNAME><LASTNAME><![CDATA[Jain]]></LASTNAME><DATE><![CDATA[24-04-1992]]></DATE><TIME><![CDATA[23:09.08]]></TIME></data></event>"; 

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = null; 
     try { 
      db = dbf.newDocumentBuilder(); 
      InputSource is = new InputSource(); 
      is.setCharacterStream(new StringReader(xmldata)); 
      try { 
       Document doc = db.parse(is); 
       //String message = doc.getDocumentElement().getTextContent(); 
       //System.out.println(message); 

       NodeList node = doc.getElementsByTagName("event"); 

      } catch (SAXException e) { 
       // handle SAXException 
      } catch (IOException e) { 
       // handle IOException 
      } 
     } catch (ParserConfigurationException e1) { 
      // handle ParserConfigurationException 
     } 
     // TODO Auto-generated method stub 
    } 
} 

谢谢,让我知道如果您需要任何更多的信息。

+0

听说过XPath? –

+0

不,你能指导我一个链接什么的? –

+0

http://www.tutorialspoint.com/xpath/index.htm –

A NodeList已经是一个包含所有请求节点的列表,但我不得不承认,我发现它的实现非常可疑。它基本上是一个包含请求节点作为子节点的节点。它的实现与其他列表实现没有什么共同之处 - 它甚至不实现List接口。我完全不知道如何处理[!CDATA],但通过所有event标签环,你不得不做这样的事情:

NodeList eventList = doc.getElementsByTagName("event"); 
for(int i = 0; i < eventList.getLength(); i++) { 
    Element eventElement = (Element) eventList.item(i); 
    // do some stuff with it 
} 

从这个元素,你也可以使用getElementsByTagName获得所需的有关信息名字等等。是的,它很可能结束与许多嵌套循环...