1
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:tns="http://www.example.org/book" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/book test.xsd ">
    <Class name="AirwayBill">
        <Attribute name="billNo" primary="true" />
        <Attribute name="date" primary="false" />
        <Attribute name="shipper" primary="false" class="Person" />
        </Class>
    <Class name="Person">
        <Attribute name="perId" primary="true" />
        <Attribute name="fname" primary="false" />
        <Attribute name="lname" primary="false" />
    </Class>
</Root>

我想读取存在属性“类”的标签的属性“名称”的属性值。我该怎么做?我正在使用 javax.xml.parsers.DocumentBuilder 和 javax.xml.parsers.DocumentBuilderFactory 类来解析和读取 xml 文件。

4

1 回答 1

0

可能有更好的方法来做到这一点,但这有效:

public static void parseXml(){
    File fXmlFile = new File("c://test.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        NodeList childList = root.getElementsByTagName("Class");
        for (int i = 0; i<childList.getLength(); i++){
            System.out.println("Class: " + childList.item(i).getAttributes().getNamedItem("name").getNodeValue());

            NodeList attList = ((Element)childList.item(i)).getElementsByTagName("Attribute");
            for (int j = 0; j<attList.getLength(); j++){
                System.out.print("  Att: " + attList.item(j).getAttributes().getNamedItem("name").getNodeValue());
                System.out.println(" primary " + attList.item(j).getAttributes().getNamedItem("primary").getNodeValue());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2014-08-11T09:21:48.510 回答