我的目標是讀取XML文件並提供一個簡單的界面,使非技術用戶能夠修改此文件。 xml文件驅動Flash照片庫,並由該Flash Actionscript預定義。使用Java讀取XML文件和獲取元素屬性時出現問題
的XML的樣本是
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<photostack3d>
<photos>
<photo>
<thumb src="Thumbs/bed1.jpg"/>
<img src="Photos/bed1.jpg"/>
<caption text="Master Bedroom"/>
<desc><![CDATA[<h1>Master Bedroom</h1><br>The master bedroom is roomy and has a beautiful view of the landscaped back yard.]]></desc>
</photo>
</photos>
</photostack3d>
在這個XML,也可以是多個節點的照片,因爲這些定義每個將由畫廊中顯示的照片...
現在,我處於使用DOM創建文件的位置,所以我們很擅長。使用DOM嘗試讀取它以進行進一步編輯是我遇到問題的地方。我可以找到所有的照片元素,但是我在處理屬性時遇到了問題,即thumb,img,caption和desc。目前,我有以下幾點:
private void loadXML(String filePath)
{
try
{
File fXmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList photosList = doc.getElementsByTagName("photos");
System.out.println("-----------------------");
NodeList photoList = doc.getElementsByTagName("photo");
System.out.println("Number of photo nodes: " + photoList.getLength());
for (int temp = 0; temp < photoList.getLength(); temp++)
{
NodeList thumbList = doc.getElementsByTagName("thumb");
Element thumbElement = (Element) thumbList.item(0);
String thumbName = thumbElement.getAttribute("thumb");
System.out.println("thumb name: " + thumbName);
//Node nNode = photoList.item(temp);
//if (nNode.getNodeType() == Node.ELEMENT_NODE)
//{
// Element eElement = (Element) nNode;
// System.out.println("Source Name : " + eElement.getAttribute("text")); //.getElementsByTagName("thumb"));
//System.out.println("Source Name : " + getTagValue("thumb", eElement));
System.out.println("-----------------------");
//}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
正如你所看到的,我一直在嘗試各種不同的方式來獲得那些屬性,但作爲然而,只是沒有看到值回來了。我哪裏錯了?
拇指,img等都是元素。 src是拇指元素/ img元素的屬性.. – Jayan 2012-04-18 04:25:54