如何使用Java读取Xml属性?

Ign*_*nox 2 java xml

给定一个如下所示的xml文档:

 <?xml version="1.0"?>
     <xml_api_reply version="1">
      <weather section="0" row="0" mobile_zipped="1" mobile_row="0"     tab_id="0" module_id="0">
        <forecast_information>
            <city data="Cordova, Andalusia"/>
            <postal_code data="cordoba"/>
            <latitude_e6 data=""/>
            <longitude_e6 data=""/>
            <forecast_date data="2012-07-18"/>
            <current_date_time data="1970-01-01 00:00:00 +0000"/>
            <unit_system data="SI"/>
         </forecast_information>
Run Code Online (Sandbox Code Playgroud)

我希望借助于显示城市数据,postal_code和日期属性System.out.println().

任何的想法?

Ign*_*nox 8

我有解决方案.我从未在此博客或其他任何内容中看到此解决方案.我希望它对其他人有用.

package Main;

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;

public class XmlTest
{

    public static void main(String argv[]) 
    {

        try 
        {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new File("xmlPrueba.xml"));
            doc.getDocumentElement().normalize();



            System.out.println("City: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(0).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Postal Code: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(1).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Date: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(4).getAttributes().getNamedItem("data").getNodeValue());

        } catch (Exception e) 
        {
            e.printStackTrace();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

还是更容易......

            System.out.println("City: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(0).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Postal Code: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(1).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Date: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(4).getAttributes().getNamedItem("data").getNodeValue());

.....
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!!!