从XML文件读取值

时间:2019-01-02 15:38:41

标签: java xml-parsing

我知道如何使用getelementbyTag来读取Java中的简单XML文件,但是我想从此处读取Java中的MAC地址01-01C-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();
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用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;

如果要导航节点,则可以。您无需对文档进行规范化,但是在查找节点时,您确实需要使用document元素,而不仅仅是使用doc。您可以获取所有的'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());
                }
            }
        }