给定一个如下所示的 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>
我想在System.out.println()
的帮助下显示城市数据、postal_code 和date 属性.
有什么想法吗?
最佳答案
我有解决方案。我从未在此博客或任何其他博客中看到过此解决方案。我希望它对其他人有用。
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();
}
}
}
或更简单 ……
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());
.....
感谢帮助!!!
关于java - 如何使用 Java 读取 Xml 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11560173/