java中的XML解析器;需要在JAVA中解析未知的XML

时间:2015-04-06 08:09:04

标签: java xml

有人可以指导一下我在java中可以使用的最佳XML解析器吗?与DOM类似,因为我已经检查过SAX,它对我没用。 此外,我需要解析未知的XML 并将该内容保存到文件中。所以JAXB也不会帮助我。

1 个答案:

答案 0 :(得分:2)

下面的类可以帮助你解析和处理你收到的xml .. jus添加导入并用xml替换字符串..

 public class XML {
        public static void main (String[] args) throws Exception {

            String xml = "<objects><student marks='one'/><student marks='two'/><school>Best school</school><teacher/></objects>";

            // parse the above xml
            InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);

            // processing it 
            Node objects = doc.getDocumentElement();
            for (Node object = objects.getFirstChild(); object != null; object = object.getNextSibling()) {
                if (object instanceof Element) {
                    Element e = (Element)object;
                    if (e.getTagName().equalsIgnoreCase("student")) {
                        String marks = e.getAttribute("marks");
                        System.out.println("It's a " + marks + " student!");
                    } else if (e.getTagName().equalsIgnoreCase("school")) {
                        String text = e.getTextContent();
                        System.out.println("It's a school that says \"" + text + "\".");
                    } else {
                        System.out.println("I don't know what a " + e.getTagName() + " is for.");
                    }
                }
            }
        }
    }

您可以使用Node的方法,如getFirstChild()和getNextSibling()来迭代子级。如果您正在解析多个文档,则可以继续重用相同的DocumentBuilder