2013-10-15 176 views
1

我是Java世界的新手,並且努力解析其中具有屬性的XML字符串。解析XML字符串

任何人都可以幫助我如何解析這個並獲得所有的數據?我的XML字符串可以根據NumOfParams更改大小。

下面是XML:

<PictureManager> 
    <FuncName>DisplayImage</FuncName> 
    <NumOfParams>2</NumOfParams> 
    <Parameters> 
     <Param type="integer">10</Param> 
     <Param type="String">C://Me.jpg</Param> 
    </Parameters> 
</PictureManager> 

我需要能夠得到「整數」和「字符串」從XML屬性也。 XML字符串可以根據< NumOfParams>

增長或縮小如果您可以發佈一些實際創建帶有上述標記的XML字符串的代碼,它將會有所幫助。

在此先感謝。

+0

嘗試先設置XML格式。沒有人會回答你的答案,如果他們不明白你的意思 – Sage

+0

你最好使用XPath來處理這種類型的XML查詢。 – tom

回答

1

在java庫中存在解析XML文檔的方法。例如這樣的:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    InputSource xml = new InputSource(); 
    xml.setCharacterStream(xmlSTring); 
    Document doc = db.parse(xml); 
    NodeList nodes = doc.getElementsByTagName("PictureManager"); 

    // iterate objects 
    for (int i = 0; i < nodes.getLength(); i++) { 
     Element element = (Element) nodes.item(i); 
     . 
     . 
     . 
    } 
+0

你可以發佈FOR循環內的代碼嗎? 我對如何獲取標籤屬性(如type =「integer」和type =「string」)感到困惑。 –

+0

我不記得文檔,只是這些類的谷歌文檔,並尋找返回參數和值的方法。 – libik

+0

@DipuKS如果你想要有整數或字符串,你可能需要使用屬性名稱查詢的「getAttribute」。請參閱我發佈的答案,並將getTextContent更改爲getAttribute,您將擁有。 – Eric

1

我的建議是從基本的步驟開始:

首先,你可能需要考慮一下你的XML文件的連接:網址是什麼?本地? 其次,你需要實例的DocumentBuilderFactory和建設者

的DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()newDocumentBuilder()。

OR

的URLConnection康恩=新的URL(URL).openConnection(); InputStream inputXml = conn.getInputStream();

DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document xmlDoc = docBuilder.parse(inputXml);

下一步是解析XML文件:

文獻XMLDOM = dBuilder.parse(XMLFILE);

之後,它會變成XML文件轉換成DOM結構或樹結構,你必須通過節點旅遊節點得到屬性內容。在你的情況下,你需要獲得內容。下面是一個例子:

String getContent(Document doc, String tagName){ 
     String result = ""; 

     NodeList nList = doc.getElementsByTagName(tagName); 
     if(nList.getLength()>0){ 
      Element eElement = (Element)nList.item(0); 
      String ranking = eElement.getTextContent(); 
      if(!"".equals(ranking)){ 
       result = String.valueOf(ranking); 
      } 

     } 
     return result; 
    } 

回報的getContent的(XMLDOM 「NumOfParams」)是 「2」。

解析完簡單的xml文件後,您可以嘗試將所有xml文件移出並打印出來。然後與SAX或JAXB聯繫。

祝你好運