我需要制作一个程序,在xml文件中输出特定元素的价格。xml文件如下所示:
<list name="root">
<book name="B1" price="30" isbn="123"/>
<list name="L1">
<book name="B2" price="20" isbn="234"/>
<list name="L2">
<cd name="C1" price="15"/>
<cd name="C2" price="5"/>
<book name="B3" price="10" isbn="345"/>
</list>
<cd name="C3" price="15"/>
<book name="B4" price="60" isbn="456"/>
</list>
</list>
我的程序应该输出如下内容:
getPrice(B1)= 30;
getPrice(L1)= B2 + L2 + C3 + B4 = 125 ...
我的想法是将名称和值存储在哈希图中,然后从中获取值。但是,我很难获得嵌套列表的价格。该程序也应适用于不同的xml文件。只有类型(cd,book和list)将是相同的。
到目前为止是我的代码:
public class ManageList implements Assignment7 {
private HashMap<String, Double> data = new HashMap<String, Double>();
@Override
public void loadXml(File input) throws Exception {
// given in the readme
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// get filename => absolute path
String filename = input.getAbsolutePath();
Document doc = db.parse(new File(filename));
// Normalize the XML Structure
doc.getDocumentElement().normalize();
// get the root element from XML document
// Element root = doc.getDocumentElement();
// ####################################
// acces elements and their attributes and store it in a hashmap
// ####################################
NodeList nl = doc.getElementsByTagName("*");
storeNodes(nl);
//System.out.println(Arrays.asList(data));
}
@Override
public Optional<Double> getPrice(String item) {
return null;
}
public void storeNodes(NodeList nl) {
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
int type = n.getNodeType();
if (type == Node.ELEMENT_NODE) {
Element e = (Element) n;
if (e.getTagName() == "book" || e.getTagName() == "cd") {
data.put(e.getAttribute("name"), Double.parseDouble(e.getAttribute("price")));
}
if (e.getTagName() == "list" && n.hasChildNodes()) {
String name = e.getAttribute("name");
//here i get a NumberFormatException
//data.put(name, Double.parseDouble(e.getAttribute("price")));
//just to show output
data.put(name, 0.0);
}
storeNodes(n.getChildNodes());
}
}
}
哈希图输出:
[{B2=20.0, C3=15.0, B3=10.0, B4=60.0, L1=0.0, L2=0.0, root=0.0, C1=15.0, B1=30.0, C2=5.0}]
如何获取嵌套列表的值?谢谢!
由于list
包含子属性,所以从nList.getLength()-1
到0
的循环将避免很多问题。