我想读取属性&#34; name&#34;的属性值。 Tag <attribute>的属性&#34; class&#34;存在..我该怎么做?</attribute>

时间:2014-08-11 07:14:23

标签: java xml xml-parsing javax.xml

<?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>

我想读取属性&#34; name&#34;的属性值。标签中的属性&#34; class&#34;存在..我该怎么做?我正在使用javax.xml.parsers.DocumentBuilder和javax.xml.parsers.DocumentBuilderFactory类来解析和读取xml文件。

1 个答案:

答案 0 :(得分: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();
    }
}