2014-12-05 118 views
0

我的XML看起来像:如何从XML中提取数据?

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

我想网络,暴民,应用程序的布尔数据和somedata作为Java字符串的Java文件。如何从XML中提取数据?请帮忙

+0

我会使用XPath:http://stackoverflow.com/questions/340787/parsing-xml-with- XPath的在Java的 – Thilo 2014-12-05 05:58:30

回答

0

你可以使用XML转换由java提供。这将返回一个名为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; 
    } 
}