2011-02-24 152 views
1

我對Android開發非常陌生,我使用的是Android 2.2,因此可以選擇使用XPath進行開發,我認爲這是一個不錯的選擇。需要Android XPath幫助

我希望提取代碼的格式爲:

<?xml version="1.0" encoding="UTF-8"?> 
<ams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<?xml-stylesheet type="text/xsl" href="XSLDoc.xsl"?> 
    <toGo> 

     <SMS> 
      <ID>1</ID> 
      <to>07700000008</to> 
      <body>Hi Alice, This is just a test message.</body> 
     </SMS> 

     <SMS> 
      <ID>2</ID> 
      <to>07700000009</to> 
      <body>Hi Bob, This is just a test message.</body> 
     </SMS> 

    </toGo> 
</ams> 

我已經看過了XPath的API和他們富的例子是不夠好,對我來說,它的工作了。任何人使用XPath收集這樣的信息,並可能將其存儲在數組列表中?

如果您覺得我的XML非常糟糕,請隨時在回覆/評論中提供更好的結構。建設性的批評歡迎!

由於提前,

編輯: 可以有0,1,2,或在一個時間產生500+ SMS塊。

+0

那麼,你想選擇哪些節點?請更好地定義問題。 – 2011-02-24 14:32:49

+0

我需要提取所有數據,最好採用以下格式: mySMSArray.add(ID,to,body); 爲每個SMS塊。 – Dech 2011-02-24 14:35:51

+0

對於將來的問題:XPath只選擇節點或者評估爲原子數據類型(XPath 1.0中的字符串,數字和布爾值)。如果你想將一些節點實例翻譯成主機語言的另一種數據類型,那麼這顯然是一種宿主語言任務。 – 2011-02-24 16:28:26

回答

1

感謝SamG指導我正確的道路,赦免雙關語。

他的答案准確率達到70%,如果沒有他的幫助,我將無法進行管理。如果其他人在解決方案之後:

ArrayList smsList = new ArrayList();

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
domFactory.setNamespaceAware(true); 
DocumentBuilder builder = domFactory.newDocumentBuilder(); 
Document doc = builder.parse("myXMLFile.xml"); 

XPath xpath = XPathFactory.newInstance().newXPath(); 

XPathExpression expr = xpath.compile("//SMS"); 

NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);  
for (int i = 0; i < nodes.getLength(); i++) { 

        NodeList items = nodes.item(i).getChildNodes(); 

        String id = items.item(1).getTextContent(); 
        String to = items.item(3).getTextContent(); 
        String body = items.item(5).getTextContent(); 

        SMS sms = new SMS(id,to,body); 

        smsList.add(sms); 
       } 

我不知道爲什麼節點得到1,3,5而不是0,1,2。但是這個解決方案對我有用,並且希望將來可以幫助其他人。如果其他人能夠解釋爲什麼它正在工作,我會非常感激地接受你的意見。

0

我會建議製作一個SMS對象並創建這些對象的ArrayList。然後你可以用這樣的東西來解析XML。

ArrayList<SMS> smsList = new ArrayList<SMS>(); 

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
domFactory.setNamespaceAware(true); 
DocumentBuilder builder = domFactory.newDocumentBuilder(); 
Document doc = builder.parse("myXMLFile.xml"); 

XPath xpath = XPathFactory.newInstance().newXPath(); 

XPathExpression expr = xpath.compile("//SMS"); 

NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); 


for (int i = 0; i < nodes.getLength(); i++) { 

    NodeList items = nodes.item(i).getChildNodes(); 

    String id = items(0).getNodeValue(); 
    String to = items(1).getNodeValue(); 
    String body = items(2).getNodeValue(); 
    SMS sms = new SMS(id,to,body); 

    smsList.add(sms);  
}