我尝试遍历您可以在下面看到的.xml文件,并检查每个用户(此处为user1和user2),如果current-tag的值与total-tag的值相同,以及则不要在current-tag的值上添加一个特定值(例如+10)。
<config>
<users>
<user1>
<name>test1</name>
<stats>
<total>50</total>
<current>50</current>
</stats>
</user1>
<user2>
<name>test2</name>
<stats>
<total>50</total>
<current>20</current>
</stats>
</user2>
</users>
</config>
我使用以下代码遍历stats
标签的子节点,并为每个用户比较current
标签的值与total
的值-标签:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(names_saves);
doc.getDocumentElement().normalize();
NodeList stats = doc.getElementsByTagName("stats");
for(int i = 0; i < stats.getLength(); i++) {
org.w3c.dom.Node n = stats.item(i);
NodeList children= n.getChildNodes();
for ( int x = 0; x < children.getLength(); x++ ) {
Node elem = children.item(x);
int current = 0;
int total = 0;
switch ( elem.getNodeName() ) {
case "current":
current = Integer.parseInt(elem.getTextContent());
break;
case "total":
total = Integer.parseInt(elem.getTextContent());
break;
}
if(current < total) {
Element element = (Element) elem;
element.getElementsByTagName("current").item(0).setTextContent(Integer.toString(current + 10));
}
}
}
此代码的问题是,它在element.getElementsByTagName(...
处引发了NullPointerException。我已经打印出了变量current
和total
的值,并且它们显示了正确的值,但是当我在if(current < total)
进行比较时,它始终是true,对于user1来说不是false对于user2为true。
最后,它应该看起来像这样:
<config>
<users>
<user1>
<name>test1</name>
<stats>
<total>50</total>
<current>50</current> <!-- Is already the same the value of total, don't edit -->
</stats>
</user1>
<user2>
<name>test2</name>
<stats>
<total>50</total>
<current>30</current> <!-- Not the same, add 10 to former value -->
</stats>
</user2>
</users>
</config>
答案 0 :(得分:1)
问题在于,当前和总计的比较是在填充两个变量的循环内进行的。因此比较是在仅填充了一个变量之后完成的。您需要将if
移到循环外,并更好地检查两个变量的值是否都设置为大于零(假设该值不能作为输入)
int current = 0;
int total = 0;
for ( int x = 0; x < children.getLength(); x++ ) {
Node elem = children.item(x);
switch ( elem.getNodeName() ) {
case "current":
current = Integer.parseInt(elem.getTextContent());
break;
case "total":
total = Integer.parseInt(elem.getTextContent());
break;
}
}
if(current > 0 && total > 0 && current < total) {
Element element = (Element) elem;
element.getElementsByTagName("current").item(0).setTextContent(Integer.toString(current + 10));
}