如何从 for 循环中获取指定的属性



我尝试获取具有最大值的 "Value" 字符串 NumVotes。之后,我想做简单的断言(我知道该怎么做(,但我在如何获得这个"值"方面遇到了问题。我对此没有想法和知识。

public class DomParserDemo {
    public static void main(String[] args) {
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader("<poll name="language_dependence" title="Language Dependence" totalvotes="170"><results><result level="1" value="No necessary in-game text" numvotes="168"/><result level="2" value="Some necessary text - easily memorized or small crib sheet" numvotes="0"/><result level="3" value="Moderate in-game text - needs crib sheet or paste ups" numvotes="0"/><result level="4" value="Extensive use of text - massive conversion needed to be playable" numvotes="0"/><result level="5" value="Unplayable in another language" numvotes="2"/></results></poll>"));
            Document doc = dbBuilder.parse(is);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("result");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                System.out.println("Level = "+ element.getAttribute("level")+", "+
                        "Value = "+element.getAttribute("value")+", "+
                        "NumVotes = "+element.getAttribute("numvotes"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

电流输出:

      Root element :poll
Level = 1, Value = No necessary in-game text, NumVotes = 168
Level = 2, Value = Some necessary text - easily memorized or small crib sheet, NumVotes = 0
Level = 3, Value = Moderate in-game text - needs crib sheet or paste ups, NumVotes = 0
Level = 4, Value = Extensive use of text - massive conversion needed to be playable, NumVotes = 0
Level = 5, Value = Unplayable in another language, NumVotes = 2

您已经在迭代所有元素。通过元素属性之一查找最大值可以通过使用变量跟踪到目前为止的最大值并将其与每个值进行比较来实现。你的 for 循环被修改了一点:

String targetValue = "";
int maxNumVotes = 0;
for (int i = 0; i < nodeList.getLength(); i++) {
    Element element = (Element) nodeList.item(i);
    int numVotes = Integer.parseInt(element.getAttribute("numvotes"));
    if (numVotes > maxNumVotes) {
        maxNumVotes = numVotes;
        targetValue = element.getAttribute("value");
    }
}
System.out.println("Value: " + targetValue + " NumVotes: " + maxNumVotes);
但是,如果要按票数对元素进行排序,

请将元素添加到列表中,然后使用比较器按票数或任何其他字段进行排序。

相关内容

  • 没有找到相关文章

最新更新