java - 如何解析带有标签内数据的 XML 字符串

标签 java parsing

我想解析这种 XML 字符串:

<Objects>
   <Object type="crs" obj_id="192">
      <Title>Course 1</Title>
      <Description>this is description</Description>
      <CreateDate>2012-10-16 12:53:12</CreateDate>
      <LastUpdate>2012-10-16 12:53:54</LastUpdate>
   </Object>

   <Object type="frm" obj_id="202">
      <Title>Forum 1</Title>
      <Description>this is description</Description>
      <CreateDate>2012-10-30 01:06:41</CreateDate>
      <LastUpdate>2012-10-30 01:06:41</LastUpdate>
   </Object>
</Objects>

我已经解析了具有相同结构但仅带有标签 的 XML 字符串。现在我想获取label Object中的信息,得到type="xxx"的字符串。

这就是我进行此类解析的方式:

try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource xml = new InputSource();
        xml.setCharacterStream(xmlSTring);
        Document doc = db.parse(xml);
        NodeList nodes = doc.getElementsByTagName("Object");

        // iterate objects 
        for (int i = 0; i < nodes.getLength(); i++) {
           Element element = (Element) nodes.item(i);
           // get first attribute
           NodeList ref_id = element.getElementsByTagName("title");
           Element line = (Element) ref_id.item(0);
           System.out.println("title: " + getCharacterDataFromElement(line));

        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
private static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "?";
}

提前致谢。

最佳答案

在你的主循环中

element.getAttribute("type");

应该能得到你想要的。

您可以使用 stax 而不是使用 dom

jee5 stax tutorial

关于java - 如何解析带有标签内数据的 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409055/