2013-06-27 141 views
3

我一直在想如何閱讀XML文件,但在你回答之前,請閱讀整篇文章。Java XML閱讀

比如我有:

<?xml version="1.0" encoding="UTF-8"?> 

<messages> 

<incoming id="0" class="HelloIlikeyou" /> 

</messages> 

我想要什麼,是從標籤獲得的所有值。我想把它放在一個字典中,這個鍵是傳入/傳出的,然後它將包含一個Pair作爲值的列表,其中id作爲關鍵字,值作爲類的值。

所以我得到這個:

HashMap<String, List<Pair<Integer, String>>> headers = new HashMap<>(); 

然後,它會在此:

HashMap.get("incoming").add(new Pair<>("0", "HelloIlikeyou")); 

但我不知道該怎麼做,我已經有了一個組成部分,但它不是工作:

File xml = new File(file); 
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(xml); 
     doc.getDocumentElement().normalize(); 

     NodeList nodes = doc.getElementsByTagName("messages"); 

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

      Node node = nodes.item(i); 

       System.out.println("Type: " + node.getNodeValue() + " packet ID " + node.getUserData("id"));  
      } 
+1

你是什麼意思 「它不是工作」(原文如此)?獲得例外?沒有返回任何數據?計算機着火? – Tenner

+0

你仍然在消息節點上運行,你必須迭代node.getChildNodes() –

+0

任何人都可以回答這個問題嗎? [此處輸入鏈路描述] [1] [1]:http://stackoverflow.com/questions/24757825/how-to-read-xml-attribute-values-hierarchically-like-parentnodename -childnodeatt –

回答

2

這是你想要什麼:

public static void main(final String[] args) 
    throws ParserConfigurationException, SAXException, IOException { 
File xml = new File(file); 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse(xml); 
doc.getDocumentElement().normalize(); 

NodeList nodes = doc.getElementsByTagName("messages"); 

for (int i = 0; i < nodes.getLength(); i++) { 
    Node node = nodes.item(i); 
    for (int j = 0; j < node.getChildNodes().getLength(); j++) { 

    Node child = node.getChildNodes().item(j); 

    if (!child.getNodeName().equals("#text")) { 
     NamedNodeMap attributes = child.getAttributes(); 

     System.out.println("Type: " + child.getNodeName() 
      + " packet ID " + attributes.getNamedItem("id") 
      + " - class: " + attributes.getNamedItem("class")); 
    } 
    } 
} 
} 

這給了我下面的輸出:

Type: incoming packet ID id="0" - class: class="HelloIlikeyou" 
+0

謝謝,但我不得不補充: if(attributes == null){ continue; } 爲了防止出現空錯誤(我的項目的工作方式,它會在一個錯誤後停止,因爲這是一個空錯誤,我得到一個錯誤)。無論如何感謝這個修復。 – user2528595

3

您可以使用JAXB,我認爲這是最好的方法。看看這個: Jaxb tutorial

+0

JAXB,imo提供了所有xml序列化庫中最糟糕的api。 XStream在api的流暢性和便利性方面遠遠優於其他。它背後的原因可能是JAXB是一個ref實現,並且不能使用像XStream這樣的奇特東西。 –

+0

請提供一個令人信服的理由使用這個特定的工具,而不是僅僅建議它。 – Mgetz

0
Node node = nodes.item(i); 
if (node instanceOf Element) { 
    Element elem = (Element)node; 
    String id = elem.getAttribute("id"); 
    ... 

所以你幾乎沒有。 W3C課程有點古老。