使用DOM解析String输入的XML

转载:http://www.rgagnon.com/javadetails/java-0573.html

关键字:DOM String XML StringReader

import java.io.StringReader;

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

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

public class ParseXMLString {public static void main(String arg[]) {
    String xmlRecords =
        "<data>" +
        " <employee>" +
        "   <name>John</name>" +
        "   <title>Manager</title>" +
        " </employee>" +
        " <employee>" +
        "   <name>Sara</name>" +
        "   <title>Clerk</title>" +
        " </employee>" +
        "</data>";

      try {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db = dbf.newDocumentBuilder();
          InputSource is = new InputSource();
          is.setCharacterStream(new StringReader(xmlRecords));

          Document doc = db.parse(is);
          NodeList nodes = doc.getElementsByTagName("employee");

          // iterate the employees
          for (int i = 0; i < nodes.getLength(); i++) {
             Element element = (Element) nodes.item(i);

             NodeList name = element.getElementsByTagName("name");
             Element line = (Element) name.item(0);
             System.out.println("Name: " + getCharacterDataFromElement(line));

             NodeList title = element.getElementsByTagName("title");
             line = (Element) title.item(0);
             System.out.println("Title: " + getCharacterDataFromElement(line));
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
      /*
      output :
          Name: John
          Title: Manager
          Name: Sara
          Title: Clerk
      */    
    }

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

 

输出:

结果: 写道
Name: John
Title: Manager
Name: Sara
Title: Clerk

 

你可能感兴趣的:(html,xml)