Java和XML:使用Java将值从文本文件更新为xml文件

时间:2015-04-16 15:50:37

标签: java

我正在创建一个java文件,该文件应该从文本文件的值更新xml文件的值。在这种情况下,库存应该减去客户购买的每种产品的数量。

文本文件:(名称,信用卡号,产品代码,数量)

Larry Lemans, 234234234, 45, 4
Gil Evans, 340934838, 45, 3
Bill Wong, 93823042, 54, 6

XML文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<inventory>
<product code="54" price="432.00" quantity= "6" />
<product code="65" price="32.00" quantity= "8"  />
<product code="45" price="31.00" quantity= "12"  />
</inventory>

所需的XML文件(在java程序更新之后):

<?xml version="1.0" encoding="ISO-8859-1"?>
<inventory>
<product code="54" price="432.00" quantity= "0" />
<product code="65" price="32.00" quantity= "8"  />
<product code="45" price="31.00" quantity= "5"  />
</inventory>

这是我到目前为止所拥有的:

import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import java.io.BufferedReader;
import java.io.FileReader;

public class inventory {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("purchases.txt"));
String line = null;

while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
UpdateInventory( purchase[2], purchase[3] );
Document doc = parser.parse("inventory.xml");
Element roote = doc.getDocumentElement();
NodeList nl = root.getChildNodes();

if (product.getAttribute("code").equals(code)){
product.setAttribute("quantity",Integer.toString

(Integer.parseInt(product.getAttribute("quantity")) - qte));
}
}
}
br.close();
}
}
TransformerFactory tfact = TransformerFactory.newInstance();
Transformer transformer = tfact.newTransformer();
transformer.setOutputProperty("encoding", "ISO-8859-1");
DOMSource source = new DOMSource(doc);
FileWriter fw = new FileWriter("inventory.xml");
StreamResult result = new StreamResult(fw);    
transformer.transform(source, result);
}
}

1 个答案:

答案 0 :(得分:0)

实现理想结果的重要步骤是:

  1. 解析源XML
  2. 解析传入的文本(CSV - 逗号分隔值)
  3. 执行计算
  4. 生成结果XML
  5. 现在您需要找到解决这些步骤的方法。我会说:去尝试,回过头来提出更详细的问题(看看https://stackoverflow.com/help/how-to-ask