2014-12-05 117 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; 
    } 
}