[英]Read a value from an XML file
我知道如何使用getelementbyTag
在 Java 中讀取一個簡單的 XML 文件,但在這里我想從這里讀取 MAC 地址,即 Java 中的 01-0C-CD-01-00-34。
我正在嘗試使用getElementsByTagName("")
,但是我應該傳入什么參數來獲取type="MAC-Address"
的元素?
<Address>
<P type="MAC-Address"xsi:type="tP_MACAddress">010C-CD-01-00-34</P>
<P type="VLAN-ID" xsi:type="tP_VLAN-ID">000</P>
<P type="VLAN-PRIORITY" xsi:type="tP_VLAN-PRIORITY">4</P>
<P type="APPID" xsi:type="tP_APPID">0001</P>
</Address>
我目前的代碼是:
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:\\Users\\User\\Desktop\\Temp\\ReadXml\\staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Address");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("MAC: " + eElement.getElementsByTagName("").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
您可以使用 xpath 查找 xml 文檔的特定部分
File fXmlFile = new File("C:\\Users\\User\\Desktop\\Temp\\ReadXml\\staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
// Create XPathExpression
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr =
xpath.compile("/Address/P[@type='MAC-Address']/text()");
// evaluate the Xpath and return result as a string.
String mac = (String) expr.evaluate(doc, XPathConstants.STRING);
System.out.println("MAC: " + mac);
Xpath 類都來自java.xml.xpath
包
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
如果你想導航節點,你可以。 您不需要規范化文檔,但在查找節點時確實需要使用文檔元素而不僅僅是文檔。 您可以獲取所有“P”標簽並查找 MAC 地址。 就像是:
NodeList nList = doc.getDocumentElement().getElementsByTagName("P");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if ("MAC-Address".equals(eElement.getAttribute("type"))) {
System.out.println("MAC: " + eElement.getTextContent());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.