parse an xml string in java?

后端 未结 4 1862
情书的邮戳
情书的邮戳 2020-12-06 00:30

how do you parse xml stored in a java string object?

Java\'s XMLReader only parses XML documents from a URI or inputstream. is it not possible to parse from a Strin

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 00:51

    Take a look at this: http://www.rgagnon.com/javadetails/java-0573.html

    import javax.xml.parsers.*;
    import org.xml.sax.InputSource;
    import org.w3c.dom.*;
    import java.io.*;
    
    public class ParseXMLString {
    
      public static void main(String arg[]) {
         String xmlRecords =
          "" +
          " " +
          "   John" +
          "   Manager" +
          " " +
          " " +
          "   Sara" +
          "   Clerk" +
          " " +
          "";
    
        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 "?";
      }
    }
    

提交回复
热议问题