我为糟糕的格式和可能愚蠢的问题道歉......我在这些领域是个菜鸟。
我创建了一个简单的 XML 文档来表示我喜欢的爱好、爱好所需的物品以及这些物品的价格。我正在编写一个 Java 应用程序来读取 XML 文件并通过使用节点输出它的内容。我已经让程序的那部分正常工作。
但是,我想弄清楚的是,是否可以取代表我已经提取的“价格”值的值,并找到它们的总和?
我已经在互联网上阅读了多个不同的线程,但它们似乎都不适合我的场景。
XML:
<?xml version="1.0"?>
<Wakeboarding>
<gear>
<description> Board </description>
<price currency = "USD"> 400.00 </price>
</gear>
<gear>
<description> Bindings </description>
<price currency = "USD"> 200.00 </price>
</gear>
<gear>
<description> Helmet </description>
<price currency = "USD"> 75.00 </price>
</gear>
<gear>
<description> Lifevest </description>
<price currency = "USD"> 75.00 </price>
</gear>
<gear>
<description> Handle </description>
<price currency = "USD"> 50.00 </price>
</gear>
</Wakeboarding>
爪哇:
public class HobbyReader
{
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
{
try
{
File fXmlFile = new File("/Users/Pete/Documents/NetBeansProjects/HobbyXML/src/hobby.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("My Hobby: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("gear");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
System.out.println("Gear Description: " + eElement.getElementsByTagName("description").item(0).getTextContent());
System.out.println("Price: " + eElement.getElementsByTagName("price").item(0).getTextContent());
}
}
输出:
run:
My Hobby: Wakeboarding
----------------------------
Gear Description: Board
Price: 400.00
Gear Description: Bindings
Price: 200.00
Gear Description: Helmet
Price: 75.00
Gear Description: Lifevest
Price: 75.00
Gear Description: Handle
Price: 50.00
预先感谢您的任何帮助!