如何从XML中提取数据?

时间:2014-12-05 05:47:48

标签: java xml java-ee xml-parsing

我的XML看起来像:

< Header>
    < Feature web="true" mob="false" app="true">some data< /feature>
< /Header>

我希望java文件包含web,mob,app in boolean中的数据,somedata作为java中的字符串。如何从xml中提取数据?请帮忙

1 个答案:

答案 0 :(得分:0)

您可以使用java提供的 XML转换。这将返回一个名为 dom对象的东西,您可以使用它来检索xml中的任何数据。在你的情况下,功能标签的一些属性和其他。

按照本教程https://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html

快速尝试的示例代码; - )

public class TransformXml {

    public static void main(String[] args) {
        String xmlStr = "<Header><feature web=\"true\" mob=\"false\" app=\"true\">some data</feature></Header>";

        Document doc = convertStringToDocument(xmlStr);

        String str = convertDocumentToString(doc);
        System.out.println(str);
    }

    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
            // "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}