[英]How can I read Xml attributes using Java?
給定一個如下所示的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和日期屬性。
任何想法?
我有解決方案。 我從未在此博客或其他任何內容中看到此解決方案。 我希望它對其他人有用。
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());
.....
謝謝您的幫助!!!
只需稍微清理類型聲明,基本空值檢查:
從'dom'值中的任何節點開始
NodeList l = dom.getElementsByTagName("tagname");
for (int j=0; j<l.getLength(); ++j) {
Node prop = l.item(j);
NamedNodeMap attr = prop.getAttributes();
if (null != attr) {
Node p = attr.getNamedItem("data");
log.debug(p.getNodeValue());
}
}
你應該看看這個:
JDOM: http : //www.javaworld.com/jw-05-2000/jw-0518-jdom.html
和
SAX: http : //en.wikipedia.org/wiki/Simple_API_for_XML
Java XML的簡單解析器
DOM和SAX都是低級API,很難使用它們。 這個問題是關於
XML中的XML解析
所以這可以通過SAX和DOM實現,但使用Apache Digester會更容易。 這也稱為數據綁定 。
希望這會幫助你。
查找XSLT。 我從來沒有使用它,但它確實是XML文檔的格式化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.