我的目标是读取 XML 文件并提供一个简单的界面,使(非技术)用户能够修改该文件。 xml 文件驱动 Flash 照片库,并由该 Flash Actionscript 预定义。
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 尝试读取它以进行进一步编辑是我遇到问题的地方。我可以访问所有照片元素,但在获取其中的属性(即拇指、图片、标题和描述)时遇到问题。目前,我有以下内容:
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();
}
}
正如您所看到的,我一直在尝试各种不同的方法来获取这些属性,但到目前为止,只是没有看到返回的值。我哪里出错了?
最佳答案
您尝试过thumbElement.getAttribute("src");
吗?
关于java - 在 Java 中读取 XML 文件和获取元素属性时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202528/