使用JDOM解析字符串xml

时间:2018-04-19 05:26:08

标签: java string sax jdom parsexml

我正在尝试使用JDOM解析字符串xml,但是当我打印它时,我打印空白。不要从我的xml字符串中打印任何数据。

    public static void main(String[] args) throws IOException {

    List resultado = null;
    resultado = new ArrayList<>();
    resultado = listarDatos();
    XStream xstream = new XStream();
    String xml = xstream.toXML(resultado);

    String adicionar = "<?xml version = \"1.0\" encoding= \"UTF-8\"?> \n";
    String doctype = "<!DOCTYPE list \n>";
    String xml_m = adicionar + doctype + xml.replace("<newwebservicematerias.Materia>", "<ListaMaterias>").replace("</newwebservicematerias.Materia>", "</ListaMaterias>");
    //System.out.println(xml_m);

    org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
    try {
        org.jdom.Document doc = saxBuilder.build(new StringReader(xml_m));
        String message = doc.getRootElement().getText();
        System.out.println(message);
    } catch (JDOMException e) {
// handle JDOMException
    } catch (IOException e) {
// handle IOException
    }

}

并尝试使用xerces和jaxp,但是他们误解了我。

1 个答案:

答案 0 :(得分:0)

代码中的getText()方法无法达到目的。它返回元素内的文本,但由于没有文本而是子元素,因此不打印所需的输出。这是修改后的代码:

package com.test;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

import com.thoughtworks.xstream.XStream;

public class JdomExample {
    public static void main(String[] args) throws IOException {

        List<String> resultado = listarDatos();
        XStream xstream = new XStream();
        String xml = xstream.toXML(resultado);
        // System.out.println("xml = " + xml);

        String adicionar = "<?xml version = \"1.0\" encoding= \"UTF-8\"?> \n";
        String doctype = "<!DOCTYPE list \n>";
        String xml_m = adicionar + doctype + xml.replace("<newwebservicematerias.Materia>", "<ListaMaterias>")
                .replace("</newwebservicematerias.Materia>", "</ListaMaterias>");
        // System.out.println("xml_m = " + xml_m);

        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            Document doc = saxBuilder.build(new StringReader(xml_m));
            // System.out.println("doc = " + doc);
            Element message = doc.getRootElement();
            print(message);
        } catch (JDOMException e) {
            // handle JDOMException
        } catch (IOException e) {
            // handle IOException
        }

    }

    public static void print(Element element) {
        XMLOutputter outp = new XMLOutputter();
        String s = outp.outputString(element);
        System.out.println(s);
    }

    private static List<String> listarDatos() {
        List<String> list = new ArrayList<>();
        list.add("hello");
        list.add("world");
        return list;
    }
}

输出:

<list>
  <string>hello</string>
  <string>world</string>
</list>