[英]Parse XML File with Java
我有一個要使用Java搜索的XML文件。 我需要通過其屬性值(端口號)找到一個元素,並返回該元素的相關描述。
已知端口的xml文件應在線托管,並具有以下架構:
<ports>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
</ports>
元素沒有唯一標識符。 在我的應用程序中,我想調用一個帶有數字作為參數的函數,它應該給我有關具有給定屬性“數字”的項目的描述。
我的問題是,它包含所有已知端口的列表,而我無法手動編輯結構以將所有端口號分配為屬性。 誰能告訴我如何解決這個問題?
提前致謝
更新:我想像get_port(int portno)
一樣搜索它。 多數民眾贊成在我的代碼 :
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMExampleJava {
public static void main(String args[]) {
try {
File input = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("record");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Port number: " + getValue("number", element));
System.out.println("Protocol: " + getValue("protocol", element));
System.out.println("Description: " + getValue("description", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
在方法內創建自己的HashMap obj,然后可以從列表中獲取所需的記錄。 例如HashMap<int itemId, List<item>> yourOwnItem = new HashMap<>();
在for循環結束時,將項目傳遞給yourOwItem,如下所示:
yourOwnItem.put(i , List<item>);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.