[英]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.