如何使用java从xml中id获取parant标签内的特定标签内容?

yhxst69z  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(148)

我有一个XML文件,如下所示。我想得到它的具体子标签从父标签使用java。

<?xml version="1.0"?>  
<class>  
    
  <question  id="scores">
        <ans>12</ans>
        <ans>32</ans>
        <ans>44</ans>
  </question>

  <question  id="ratings">
        <ans>10</ans>
        <ans>22</ans>
        <ans>45</ans>
        <ans>100</ans>
  </question>
<default>
    Sorry wrong
</default>
  </class>

我希望函数像这样

String function(String id)

它将随机返回ANS标记
也就是说,如果我给予input id=scores,程序将在XML标记中查找id作为scores,并获取其子节点的length(),在本例中为3,然后随机返回,如32或44或12。
我的代码到目前为止

public class ChatBot {
    
    private String filepath="E:\\myfile.xml";
    private File file;
    private Document doc;

    public ChatBot() throws SAXException, IOException, ParserConfigurationException {
         file = new File("E:\\myfile.xml");  
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
         DocumentBuilder db = dbf.newDocumentBuilder();  
         doc = db.parse(file); 
    }
    
    
    String Function(String id){
// This part
            return null;
    }
       
    }
kknvjkwl

kknvjkwl1#

正如@LMC所建议的(因为org.w3c.dom.Document.getElementById()不能将任意的id属性识别为getElementById()的ID,也不能将其识别为浏览器的ID,主要是HTML语义/格式),可能:

String Function(String id) throws XPathExpressionException {
        XPath xPath = XPathFactory.newInstance().newXPath();
        // Be aware: id inserted without any escaping!
        NodeList parents = (NodeList)xPath.evaluate("/class/question[@id='" + id + "']", doc, XPathConstants.NODESET);

        if (parents.getLength() < 1) {
            return null;
        } else if (parents.getLength() > 1) {
            // Huh, duplicates?
        }

        Element parent = (Element)parents.item(0);
        NodeList children = parent.getChildNodes();

        List<Element> answers = new ArrayList<Element>();

        for (int i = 0, max = children.getLength(); i < max; i++) {
            if (children.item(i).getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if (children.item(i).getNodeName().equals("ans") != true) {
                // Huh?
                continue;
            }

            answers.add((Element)children.item(i));
        }

        if (answers.size() <= 0) {
            return null;
        }

        int selection = (int)(Math.random() * answers.size());

        return answers.get(selection).getTextContent();
    }

相关问题